How to communicate between an iframe and the parent page

From parent page -> iframe

In the parent page:

js
const iframe = document.getElementById('iframe'); iframe.contentWindow.postMessage('some message', '*');

In the iframe:

js
window.onmessage = function(e) { if (e.data === 'some message') { alert('It works!'); } };

From iframe -> parent page

In the parent page:

js
window.onmessage = function(e) { if (e.data === 'from iframe') { alert('It works!'); } };

In the iframe:

js
window.top.postMessage('from iframe', '*')

Source