Skip to content

Instantly share code, notes, and snippets.

@ger86
Created February 20, 2020 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ger86/a23df2c1a59d085c3682e5ae4d3e3c54 to your computer and use it in GitHub Desktop.
Save ger86/a23df2c1a59d085c3682e5ae4d3e3c54 to your computer and use it in GitHub Desktop.
/************************************************
*
* 📩📩📩 window.postMessage() 📩📩📩
*
* The window.postMessage() method safely enables cross-origin communication
* between Window objects; e.g., between a page and a pop-up that it spawned,
* or between a page and an iframe embedded within it.
*
************************************************/
// Syntax
targetWindow.postMessage(
message, // some object
targetOrigin // URI of the recipient page
);
// Sender.js
const message = {foo: 'foo', bar: 'bar'};
const childWindowName = 'popup';
let childwin = null;
function openChildWindow() {
childwin =
window.open('Receiver.html', childWindowName, 'height=300px, width=500px');
}
function sendMessage() {
if (childwin) {
// ⚠️⚠️⚠️ DO NOT use '*' in production
childwin.postMessage(message, '*')
childwin.focus();
}
}
// Receiver.js
// Event listener to receive messages
window.addEventListener('message', event => {
if (event.origin === 'mydomain.com') {
const message = event.data;
console.log(message); // {foo: 'foo', bar: 'bar'};
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment