Today I Learned

hashrocket A Hashrocket project

Receive Javascript messages from iFrame

Due to security reasons what can be received from an iFrame can be very limited. However there is a utility built for the purpose of safely communicating with things like an iFrame, pop-up, etc.

An iframe can utilize the Window.postMessage() function to post info that may be relevant to someone embedding the iFrame.

Then in the page where the embedded iFrame is located, the message event can be watched.

window.addEventListener("message", (event) => {
  if (event.origin !== "IFRAME URL")
    return;

  // ...
}, false);

By utilizing the event's origin you can be even safer. Above we're declaring that if the origin of tghe event did not come from the expected iframe's url... just stop.

If you're good with the origin check then looks at the event's data property. It will provide whatever was sent via postMessage().

See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.