JavaScript Internals (521 Qs)•Part 1: Core Objects, Prototypes, Functions & Scope (1 - 53)
What is a post message
Post message is a method that enables cross-origin communication between Window objects.(i.e, between a page and a pop-up that it spawned, or between a page and an iframe embedded within it). Generally, scripts on different pages are allowed to access each other if and only if the pages follow same-origin policy(i.e, pages share the same protocol, port number, and host).
Practical Code Example
javascript
// Sending Window (e.g. Parent window sending to iframe)
const iframe = document.getElementById('myIframe');
iframe.contentWindow.postMessage({ action: 'GREET', msg: 'Hello IFrame' }, 'https://trusted.com');
// Receiving Window (in iframe)
window.addEventListener('message', (event) => {
// Always verify origin for security!
if (event.origin !== 'https://trusted.com') return;
console.log('Received message:', event.data);
});