Passing events between a window and an iframe — by Steven Lacerda (Morgan Hill, CA)
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!