Reputation: 12388
I have multiple iframes in a page. Now I have one message
event listener for the page, which gets the messages from all of the iframes. I have a workaround to know from which iframe the message is coming.
I would like to make event listeners for each iframe separately. Is this possible?
Upvotes: 42
Views: 63801
Reputation: 2593
You must listen on the global message
event of the window
object, but you can filter the source iframe using the source
property of MessageEvent
.
Example:
const childWindow = document.getElementById('test-frame').contentWindow;
window.addEventListener('message', message => {
if (message.source !== childWindow) {
return; // Skip message in this event listener
}
// ...
});
Upvotes: 110
Reputation: 1043
I would like to make event listeners for each iframe separately. Is this possible?
This is very possible if you're willing to give each frame a dedicated MessageChannel
.
Doing so will also make your program less vulnerable to certain CSRF attacks if your codebase starts to get more complex, as well as marginally more performant, since you only have to put your major authenticity checks in 1 place (making sure the channel is established securely) rather than having to weave your major authenticity checks into a general-purpose bastion message handler on the child.
async function openSecureChannel_a(exactWindow) {
const { port1, port2 } = new MessageChannel();
const { port1: meta_port1, port2: meta_port2 } = new MessageChannel();
await new Promise((resolve, reject) => {
meta_port1.onmessage = ((event) => {
switch (event.data.command) {
case 'ok':
resolve();
break;
default:
reject(new Error('Unexpected response.', { cause: event.data }));
break;
}
});
exactWindow.postMessage({
command: 'openSecureChannel',
port: port2,
meta_port: meta_port2
}, { transfer: [port2, meta_port2], targetOrigin: '*' });
setTimeout(() => reject(new DOMException('The operation timed out.', 'TimeoutError')), 2718.2818284590453);
});
return port1;
}
async function openSecureChannel_b(expectedOrigin) {
if (expectedOrigin === undefined)
expectedOrigin = location.origin;
return await new Promise((resolve, reject) => {
window.addEventListener('message', ((event) => {
if (event.origin !== expectedOrigin && expectedOrigin !== '*')
return;
switch (event.data.command) {
case 'openSecureChannel':
if (event.data.port instanceof MessagePort) {
event.data.meta_port.postMessage({
command: 'ok'
});
resolve(event.data.port);
} else {
event.data.meta_port.postMessage({
command: 'error',
message: `Expected type MessagePort, got type ${Object.getPrototypeOf(event.data.port).constructor.name}.`
});
}
}
}));
setTimeout(() => reject(new DOMException('The operation timed out.', 'TimeoutError')), 2718.2818284590453);
});
}
<p>Demo:</p>
<script type="module">
let frame = document.createElement('iframe');
frame.src = `data:text/html,%3Cscript type="module"%3E
${openSecureChannel_b.toString().trim()};
const securePort_inIFrame = await openSecureChannel_b();
securePort_inIFrame.onmessage = ((event) => {
const p = document.createElement('p');
const s = \`Got message from parent: \$\{JSON.stringify(event.data)\}\`;
p.appendChild(document.createTextNode(s));
document.body.appendChild(p);
});
securePort_inIFrame.postMessage("Oh, by the way, these channels are bidirectional!");
%3C/script%3E`;
document.body.appendChild(frame);
await new Promise((resolve) => frame.addEventListener('load', () => resolve(), { once: true }));
const securePort_inParent = await openSecureChannel_a(frame.contentWindow);
securePort_inParent.onmessage = ((event) => {
const p = document.createElement('p');
const s = `Got message from child: ${JSON.stringify(event.data)}`;
p.appendChild(document.createTextNode(s));
document.body.appendChild(p);
});
securePort_inParent.postMessage("HELLO FROM THE PARENT!");
securePort_inParent.postMessage("This messagePort can be re-used!");
</script>
Upvotes: 0
Reputation: 1
I implemented an iframe proxy. Iframe with in an iframe ( nesting them ). Each iFrame proxy creates it's own unique I'd. Than every message that is sent from child iframe to parent is gets an added field of the iframe proxy I'd. In the parent you then route every message from the iframeproxy to it's dedicated handler. This mechanism separate iframes perfectly
Upvotes: 0
Reputation: 16587
Actually you can. Add a unique name attribute to each iframe. iframe name is passed down to the contentWindow. So inside iframe window.name is the name of the iframe and you can easily send it in post message.
Upvotes: 9
Reputation: 3408
One way of detecting where the message came from is by checking which iframe is focused or for my specific scenario which iframe is visible.
Upvotes: 1
Reputation: 2943
You could use e.originalEvent.origin
to identify the iframe.
On the iframe child:
window.parent.postMessage({
'msg': 'works!'
}, "*");
On the iframe parent:
Javascript
window.addEventListener('message', function(e) {
console.log(e.origin); // outputs "http://www.example.com/"
console.log(e.data.msg); // outputs "works!"
if (e.origin === 'https://example1.com') {
// do something
} else if (e.origin === 'https://example2.com'){
// do something else
}
}, false);
jQuery
$(window).on('message', function(e) {
...
}, false);
So origin
contains the protocol and domain from which the postMessage()
was fired from. It does not include the URI. This technique assume all iframes have a unique domain.
Upvotes: 4
Reputation: 2943
If the src
attribute of each iframe is unique then you can try this:
On the child:
function sendHeight() {
// sends height to parent iframe
var height = $('#app').height();
window.parent.postMessage({
'height': height,
'location': window.location.href
}, "*");
}
$(window).on('resize', function() {
sendHeight();
}).resize();
On the parent:
$(window).on("message", function(e) {
var data = e.originalEvent.data;
$('iframe[src^="' + data.location + '"]').css('height', data.height + 'px');
});
The child sends it's height and URL to the iframe parent using postMessage()
. The parent then listens for that event, grabs the iframe with that URL and sets the height to it.
Upvotes: 12
Reputation: 18762
No, it's not possible. Best you can do is to have a single handler that routes received messages to helper handlers based on the origin of the message sender.
Upvotes: 1