Imagine this: you have a parent page with a login button and a popup in which your user enters credentials. How do you signal the parent page when the user logged in? Use postMessage.

In popup code when your user logs in call the postMessage method

window.opener.postMessage({key: 'value'}, 'http://trusted.origin')

The first parameter is data you want to send and the second is the origin that the message is intended for, so if you send credentials through postMessage pages that are not on the specified origin will not receive them. You can set the second parameter to * to bypass any checks.

In parent page code you can listen for messages using

window.addEventListener('message', function (ev) {
	console.log(ev)
})

ev.data contains data you sent and ev.origin contains the origin of data. Easy! If you want to send data the other way (parent to popup) then use w.postMessage where w is popup window object. To listen on the popup side, use the same code as on the parent side.

Liked this article? Share it! Also, you can support me on Patreon