乐闻世界logo
搜索文章和话题

How does iframe implement cross-domain communication? What are the usage methods and security considerations of the postMessage API?

3月7日 19:39

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

javascript
window.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

javascript
window.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

javascript
const 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

javascript
window.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

  1. Cross-domain Communication: Data exchange between pages under different domains
  2. Third-party Integration: Status synchronization when embedding third-party services (such as payment, login)
  3. Responsive Adjustment: iframe content notifies parent page to adjust based on its own size
  4. Single Sign-on: Passing authentication information between different domains
  5. Real-time Data Updates: Child pages push real-time data to parent page

Important Notes

  1. Same-Origin Policy Restrictions: postMessage is not restricted by the same-origin policy, but targetOrigin needs to be set correctly
  2. Message Serialization: Sent data will be structurally cloned, and certain objects (such as functions, DOM nodes) cannot be sent
  3. Performance Considerations: Frequent message passing may affect performance, it is recommended to batch process or use debounce
  4. Error Handling: Add appropriate error handling mechanisms to prevent malicious messages from causing security issues
标签:Iframe