title: Security concerns with window.postMessage() + iframes + developer tools
body: <p>I've read up on how to avoid security issues when using <code>window.postMessage()</code> -- particularly the suggestions in this <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" rel="nofollow noreferrer">MDN doc</a>.</p>
  
  <p>But given all the preventative tips are all client-side, I'm having trouble understanding how they'd stop bad actors from simply editing changing the code in their developer tools.</p>
  
  <p>Here's the situation I'm dealing with. I have a page that will contain an embedded iframe, and I have control over that iframe (it lives on a separate domain, but the vendor that provides it allows me to put custom JavaScript in the iframe source). The parent window and the iframe will communicate back and forth.</p>
  
  <pre><code>/**
    window at https://firstgoodorigin.com
  
    Receives message from iframe to indicate
    its contents have loaded.
  
    Once that message has been received,
    send a message back to the iframe.
  */
  function handleMessage(message) {
    if (message.origin === 'https://secondgoodorigin.com') {
      // verify and sanitize what's in message.data
      // (it'll be something like "loaded")
      // if it's good, send a message back
      message.source.postMessage('foo', 'https://secondgoodorigin.com');
    }
  }
  
  window.addEventListener('message', handleMessage, false);
  
  
  /**
    iframe at https://secondgoodorigin.com
  
    Tell parent window it has loaded. Once that happens
    it will receive a message from the parent window, for
    which we add an event listener.
  */
  window.addEventListener('load', () =&gt; {
    window.parent.postMessage('loaded', https://firstgoodorigin.com);
  });
  
  window.addEventListener('message', (message) =&gt; {
    if (message.origin === 'https://firstgoodorigin.com') {
      // verify and sanitize what's in message.data
      // do stuff
    }
  });
  </code></pre>
  
  <p>Given both the window source and iframe source will be editable inside someone's web inspector, what's to stop them from removing all the validation logic and replacing it with something malicious? What am I missing here?</p>