postMessage is a cross-document messaging API provided by HTML5 that allows secure communication between windows of different origins, including communication between iframes and parent pages.
Basic Syntax
javascript// Send message otherWindow.postMessage(message, targetOrigin, [transfer]); // Receive message window.addEventListener('message', (event) => { // Handle message });
Parameter Description
- message: The data to send, which can be any serializable object
- targetOrigin: The origin of the target window, which can be a specific URL, "*" (all origins), or "/" (same origin)
- transfer: Optional, a set of transferable objects for transferring ownership
Security Best Practices
1. Always Verify Message Source
javascriptwindow.addEventListener('message', (event) => { // Verify message source if (event.origin !== 'https://trusted-domain.com') { return; } // Handle message const data = event.data; });
2. Use Specific targetOrigin
javascript// Not recommended: allow all origins iframe.postMessage(data, '*'); // Recommended: specify specific origin iframe.postMessage(data, 'https://trusted-domain.com');
3. Verify Message Data Format
javascriptwindow.addEventListener('message', (event) => { if (event.origin !== 'https://trusted-domain.com') { return; } // Verify data structure if (!event.data || typeof event.data.type !== 'string') { return; } switch (event.data.type) { case 'resize': handleResize(event.data); break; case 'close': handleClose(); break; } });
iframe and Parent Page Communication Examples
Parent Page Sends Message to iframe
javascriptconst iframe = document.getElementById('myIframe'); // Wait for iframe to load iframe.onload = () => { iframe.postMessage({ type: 'init', data: { userId: 123, token: 'abc123' } }, 'https://child-domain.com'); };
iframe Sends Message to Parent Page
javascript// Code inside iframe window.parent.postMessage({ type: 'resize', data: { width: 800, height: 600 } }, 'https://parent-domain.com');
Parent Page Receives iframe Message
javascriptwindow.addEventListener('message', (event) => { if (event.origin !== 'https://child-domain.com') { return; } if (event.data.type === 'resize') { const iframe = document.getElementById('myIframe'); iframe.style.width = event.data.data.width + 'px'; iframe.style.height = event.data.data.height + 'px'; } });
Common Use Cases
- Cross-domain Communication: Data exchange between pages under different domains
- Third-party Integration: Status synchronization when embedding third-party services (such as payment, login)
- Responsive Adjustment: iframe content notifies parent page to adjust based on its own size
- Single Sign-on: Passing authentication information between different domains
- Real-time Data Updates: Child pages push real-time data to parent page
Important Notes
- Same-Origin Policy Restrictions: postMessage is not restricted by the same-origin policy, but targetOrigin needs to be set correctly
- Message Serialization: Sent data will be structurally cloned, and certain objects (such as functions, DOM nodes) cannot be sent
- Performance Considerations: Frequent message passing may affect performance, it is recommended to batch process or use debounce
- Error Handling: Add appropriate error handling mechanisms to prevent malicious messages from causing security issues