Passing events between a window and an iframe — by Steven Lacerda (Morgan Hill, CA)

Steven Lacerda
2 min readAug 9, 2018

--

Iframes by default will not listen to an event from the parent window inside the iframe, so you will actually have to listen in the parent window and pull it into your iframe. Well, how is that done…you can do something like this:

Let’s throw a custom event within our parent window:

var event = new CustomEvent('data', {
detail: Object.assign(options, {
type: 'env'
})
});

document.dispatchEvent(event);

Okay, the above code throws an event, in my case I use a proprietary system, so it throws on some event. But, you could throw within an eventListener.

Now, to receive the event within the iframe, we have to write something like this:

const frameEl = window.frameElement;
const parentWindow = frameEl.contentWindow.parent;

parentWindow.document.addEventListener('selection-updated', (evt)=> {
if (parentWindow.selectedObjectName && parentWindow.selectedMetric) {
getData(7);
}
});

So, what’s happening? This code block would be within a <script> tag inside my iframe, and it’s basically reaching out to the parent window using the window.frameElement tag, grabbing the parent as window.frameElement.contentWindow.parent and listening for events there.

Does this make sense? We are basically working our way around the fact that an event does not make it into the iframe by going outside of the iframe and listening on the parent, but since we’re doing that from within our iframe we have access to the data within our iframe.

Cool workaround right! Anyhow, hope this helped.

Solving a problem is as good as those sexual feelings…sometimes, okay, maybe not. Straight from Morgan Hill, CA. Good luck!

— by Steven Lacerda

--

--

Steven Lacerda
Steven Lacerda

Written by Steven Lacerda

Steve Lacerda is a software engineer specializing in web development. His favorite 80’s song is Let’s Put the X in Sex by Kiss.

No responses yet