How to pass an event to parent DOM from Iframe using JavaScript?

The communication between the parent DOM and Iframes are sometimes complex due to the fact that iframes are separate DOM under the parent DOM. It is possible to pass an event from iframe to parent DOM and at the same time from parent DOM to iframe. Communication can happen both ways.

In this post, we are going to show how to we can pass message events from iframe to parent DOM. To pass the event we need to have control over both the iframe and the parent DOM.

In the case of cross-origin or cross-domain where we do not have control over the iframe or parent DOM then the following approach is not possible. We need to be able to write the script in both places.

Script for iframe

document.getElementById('expired-paywall').addEventListener('click', function (e) {
    window.parent.postMessage('subscribe', '*');
}, false);

Script for parent DOM

// Listen to message from child window
window.addEventListener('message', function (event) {
    console.log(event)
    if(event.data === 'subscribe'){
        console.log('Set subscribe event');
    }
}, false);

Reference:

Share