andy pai's tils

Pushing Data to Parent Window from an iframe

Today, I needed to push an object from within an iframe to the parent window's dataLayer. Here's what I learned:

Same-Origin Scenario

If the iframe and the parent window are on the same domain, you can directly access the parent window's dataLayer and push objects to it:

// Object you want to push
const dataObject = { event: 'eventName', property: 'value' };

// Check if the parent window is accessible
if (window?.parent?.dataLayer) {
  // Push the object to the parent window's dataLayer
  window.parent.dataLayer.push(dataObject);
} else {
  console.log('Cannot access parent dataLayer');
}

If there are several nested iframes nested, you can use window.top to refer to the topmost window in the window hierarchy from an iframe. window.top points to the topmost window in the hierarchy of window frames, which is essentially the window that contains all other nested frames or iframes.

Cross-Origin Scenario

If the iframe and the parent window are on different domains, you need to use the postMessage method to securely communicate between them:

In the iframe (requesting the URL):

// Send a message to the parent window requesting the URL
window.top.postMessage({ request: 'getUrl' }, '*');

In the top window (providing the URL):

// Listen for messages in the top window
window.addEventListener('message', (event) => {
  if (event.origin !== "http://example.com") {
    return; // Always validate the origin
  }

  if (event.data.request === 'getUrl') {
    // Send back the URL or specific parts of it as needed
    event.source.postMessage({ url: window.location.href }, event.origin);
  }
}, false);

Back in the iframe (receiving the URL and pushing to dataLayer):

// Listen for the response in the iframe
window.addEventListener('message', (event) => {
  if (event.origin !== "http://example.com") {
    return; // Validate the origin
  }

  if (event.data.url) {
    // Push the received URL to the parent's dataLayer
    window.top.postMessage({ type: 'dataLayer', data: { url: event.data.url } }, event.origin);
  }
}, false);

Key Takeaways