Sam Sam - 1 year ago 139
Javascript Question

Find surrounding element of source iframe in addEventListener

I have a shell page that contains a number of sandboxed iframes.


<div id="sb1"><iframe sandbox="allow-scripts" srcdoc="stuff here"/></div>
<div id="sb2"><iframe sandbox="allow-scripts" srcdoc="other stuff here"/></div>

When I receive a message from one of the iframes I'd like to know the parent div (i.e. #sb1 or #sb2).

I have tried the following but it doesn't work:

function receiveMessage(event)
// Follow line results in : Uncaught DOMException: Blocked a frame with origin ...
var parentDiv = $(event.source).parent();

window.addEventListener("message", receiveMessage);

Is there a way to determine the iframe's parent without having to pass an id in the message from the iframe?

Sam Sam
Answer Source

I was able to get this to work based on "Alexander O'Mara" comment.

function receiveMessage(event)
  var parentDiv = $($('iframe').toArray().find(
      function(f) {
        return f.contentWindow === event.source;

window.addEventListener("message", receiveMessage);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download