Trying to pass a message from an amp-iframe back to its parent window

90 Views Asked by At

I have an amp-iframe displaying and working fine, its content is hosted on a different domain, all is good.

Once a button is clicked the amp-iframe sets a few cookies and closes, I want to pass a message to the parent window using passMessage(), unfortunately that does not seem to be working at all.

This is the content loaded into the amp-iframe:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Test Cookie consent</title>

  <script type="text/javascript">
    window.addEventListener('load', (e) => {

      const checkCookieTimer = setInterval(() => {
        if (document.cookie.split(';').some((item) => item.trim().startsWith('BANNER_VIEWED=1'))) {
          const cookie = document.cookie;
          console.group('consent iframe');
          console.log('window load event', e);
          console.log('cookie', cookie);
          console.log('window', window);
          console.groupEnd();

          window.top.postMessage({ message: cookie }, 'https://consent-test.domain.com');

          clearInterval(checkCookieTimer);
        }
      }, 500);

    });
  </script>
</head>

<body>
</body>

</html>

And this is the code In the page that waits for the message

<amp-iframe title="Consent" class="ens-iframe" resizable
    sandbox="allow-scripts allow-popups allow-top-navigation allow-same-origin allow-popups-to-escape-sandbox"
        frameborder="0" layout="fill" src="https://consent-test.domain.com">
    <div overflow tabindex="0" role="button" aria-label="Show more">Click to show more</div>
    <amp-img layout="fill" src="/dist/images/spacer.gif" placeholder></amp-img>
    <script async custom-element="amp-consent" src="https://cdn.ampproject.org/v0/amp-consent-0.1.js"></script>

    <script type="text/javascript">
        window.addEventListener('message', function (event) {
            console.log(event);
        });
    </script>
</amp-iframe>
0

There are 0 best solutions below