Petrus Borel
Petrus Borel

Reputation: 1

postMessage to iFrame not working through GTM

I'm facing a strange situation. I wrote a code which should send a variable to an iFrame embedded on my page through postMessage().

The parent-page is: "https://www.bestcars.com (example) The iFrame-page is: "https://info.bestcars.com (example)

I triggered the following code in GTM when the parent-page is loaded:

(function(window) {
     var checkIframe = setInterval(function() {
         var iframe = document.querySelector('.p-form-content'); 
         var urlobject = "Hello";
         iframe.contentWindow.postMessage(urlobject, 'https://info.bestcars.com');
         clearInterval(checkIframe);
      }, 100); 
})(window);

But, that doesn't work. The console shows the error-message:

VM1359:1 Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('https://info.bestcars.com') does not match the recipient window's origin ('https://www.bestcars.com').

The strange thing: it works when I'm executing the same code on the same page through the console in Chrome.

Can you help?

Thanks,

Upvotes: 0

Views: 50

Answers (1)

chrwahl
chrwahl

Reputation: 13145

Maybe you need to wait for the document in the iframe to be loaded? Here is an example where the document of the iframe looks like this:

<!DOCTYPE html>
<html>
  <head>
    <script>
      window.addEventListener('message', e => {
        document.body.innerHTML += `<div>${e.data}</div>`;
      });
    </script>
  </head>
  <body>
    <p>test</p>
  </body>
</html>

And use the load event on the iframe:

document.querySelector('iframe').addEventListener('load', e => {
  setInterval(function(){
    e.target.contentWindow.postMessage('hello', '*');
  }, 1000);
});
<iframe src="data:text/html;base64,PCFET0NUWVBFIGh0bWw+CjxodG1sPgogIDxoZWFkPgogICAgPHNjcmlwdD4KICAgICAgd2luZG93LmFkZEV2ZW50TGlzdGVuZXIoJ21lc3NhZ2UnLCBlID0+IHsKICAgICAgICBkb2N1bWVudC5ib2R5LmlubmVySFRNTCArPSBgPGRpdj4ke2UuZGF0YX08L2Rpdj5gOwogICAgICB9KTsKICAgIDwvc2NyaXB0PgogIDwvaGVhZD4KICA8Ym9keT4KICAgIDxwPnRlc3Q8L3A+CiAgPC9ib2R5Pgo8L2h0bWw+"></iframe>

Upvotes: 0

Related Questions