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

How do you use window.postMessage across domains?

1个答案

1

window.postMessage is a powerful Web API used for securely enabling cross-origin communication between different origins (domains, protocols, or ports). Using postMessage can mitigate traditional cross-origin communication risks and ensure that both the sender and receiver can verify the trustworthiness of the source.

Usage Steps

  1. Sending a Message: First, on the page sending the message (parent page or source page), call the window.postMessage() method. This method accepts two main parameters: the message to send and the target window's origin.

    Example Code:

    javascript
    // Assume childWindow is a reference to an opened child window var message = 'Hello, this is parent!'; var targetOrigin = 'https://example.com'; // Specify the domain that will receive the message childWindow.postMessage(message, targetOrigin);
  2. Receiving a Message: On the target page (child page or receiving page), set up an event listener to handle received messages. This is primarily done by listening for the message event.

    Example Code:

    javascript
    window.addEventListener('message', function(event) { // Verify the message source matches the expected domain if (event.origin !== "https://trusteddomain.com") { console.log('Received message from unauthorized domain:', event.origin); return; // Ignore messages from unverified sources } // Process the received data console.log('Received data:', event.data); }, false);

Security Considerations

When using window.postMessage, several security considerations must be noted:

  • Always verify event.origin: When receiving a message, always verify the event.origin property to ensure it matches the expected sender domain. Do not process messages from unverified sources.
  • Define targetOrigin carefully: When sending messages, ensure targetOrigin is strictly defined to avoid using "*" (which allows any domain to receive messages) unless in very specific cases.

In this way, window.postMessage can be safely used for cross-origin communication while ensuring data integrity and security. In practical applications, this method is commonly used for communication between the parent page and embedded iframes or with service workers.

2024年7月26日 21:43 回复

你的答案