1
\$\begingroup\$

I am trying to enable communication via JavaScript from an iframe and its parent window when they are on different domains. I did a lot of research and it turned out that postMessage() is a good approach if used correctly. I have read the vast resources about how to use it to make sure it’s implemented in a secure way and came up with the code. However, as I am still new to coding, I am paranoiac about XSS vulnerabilities and this code looks too simple to me to be fully secure. I would appreciate if someone can review it.

Context:

  • The message must be sent from the iframe to the parent window only
  • The iframe is HTTPS, while the parent is HTTP
  • The message doesn’t contain sensitive data – it’s just a simple indicator for the parent window to do trigger a google tag manager custom event
  • Parent window domain in the example is: http://my-main-web.com
  • Iframe domain in the example is: https://my-iframe-web.com

Questions:

  • Is the code exposed to security risks?
  • Are there other risks apart that the attacker might find out the message content is 'download'? For example, can meticulous code be injected through the message?

Sender (iframe):

<script type="text/javascript">
  parent.postMessage("download occurred", "http://my-main-web.com");
</script>

Receiver (parent window):

<script type="text/javascript">
  function receiveMessage(event) {
    if(event.origin !== “https://my-iframe-web.com”) return; // validate origin

    if (event.data !== "download occurred") return; // validate message content
      console.log(“msg received”);
      window.dataLayer = window.dataLayer || [];
      window.dataLayer.push({
        'event': 'download' // create custom GTM event
      });
    };

  window.addEventListener("message", receiveMessage, false);
</script>
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.