Created
February 20, 2020 06:56
-
-
Save ger86/a23df2c1a59d085c3682e5ae4d3e3c54 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/************************************************ | |
* | |
* 📩📩📩 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