Lukas' Notes

web security

Definition

postMessage

postMessage is a Web API that enables cross-origin message exchanges between windows, for example between a parent page at a.com and an iframe it embeds from b.com. Each message carries a data payload and an origin field identifying the sender.

Validate the Originn

Validate the origin

Receivers must check event.origin against an expected value before acting on event.data. Skipping that check turns any window that can post a message into an untrusted source, which typically yields a cross-origin XSS-class vulnerability.

// on a.com, embedding an iframe from b.com
window.addEventListener('message', (evt) => {
  if (evt.origin === 'http://b.com') {
    console.log(evt.data);   // only trust b.com
  }
});
// on b.com, the iframe, posting back up
window.parent.postMessage('hello!', 'http://a.com');