netdjw
netdjw

Reputation: 5997

How to detect JavaScript postMessage source iframe's id?

I have this code:

<iframe src="..." id="iframe_01"></iframe>
<iframe src="..." id="iframe_02"></iframe>
const eventMethod = window.addEventListener ? 'addEventListener' : 'attachEvent';
const eventer = window[eventMethod];
const messageEvent = eventMethod === 'attachEvent' ? 'onmessage' : 'message';

eventer(messageEvent, (e) => {
  console.log(e);
  // ...
});

What is the best way to detect the message sender iframe's id?

Upvotes: 2

Views: 1645

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1073969

Two ideas:

  1. You might be able to get it by comparing the message source with the contentWindow property of the iframe elements (e.g., in a loop). You'd want to try this out on all of your target browsers to make sure that event.source === iframe.contentWindow works to identify the iframe.

  2. You could have the iframe explicitly include it in the message. The iframe's window should have access to the iframe element it's embedded in via the frameElement property so in theory, at least for same-origin windows, frameElement.id would give the iframe that ID.

If neither of those works, you could use postMessage to tell the iframes what ID to send back, or include the ID in the query string of the iframe's URL so the iframe can get it from location.search.

Upvotes: 3

Related Questions