嘿, 我是Mofei!
Window.postMessage() HTML5 Cross-Origin Solution

Hey, everybody~

It's the unfortunate cross-domain issue again T T , how many people have failed at the interview question "Tell me what cross-origin solutions you know, the more the better?"

Today, I want to discuss a cross-origin solution provided by HTML5, Window.postMessage. It is easy to learn and use, and will certainly impress you. However, in most cases, it won't keep you smiling for long. As the saying goes, "the higher the level, the more powerful the magic", this method is also limited by certain HTTP protocols, such as X-Frame-Options:SAMEORIGIN. Fortunately, in most cases, the situation is not that bad. Let's get to the point:

Window.postMessage provides a secure cross-origin communication solution.

Syntax


The syntax is divided into two parts: sending and receiving, both of which are quite simple.

Sending

otherWindow.postMessage( message , origin [ , transfer] )

* otherWindow

A reference to the cross-origin window object, such as an iframe, or an object created by window.open, etc.

* message

The message sent to the cross-origin object, which can be a string, object, number, etc.

* origin

Specifies the domain name of the message sender, with a wildcard * allowed.

Receiving

We can listen for the window's "message" event to get the received value, for example:

window.addEventListener('message',receiveMessage,false);

function receiveMessage(event){
    // ...
}

The received event includes several important properties:

* data

The information passed over.

* origin

The domain name of the sender, including the protocol and port (e.g., https://developer.mozilla.org:443), the default port is usually omitted, for example https://www.google.com means port 443 is omitted, http://www.google.com omits port 80.

* source

A reference to the window that sent the data, for example, if domain B receives a message from domain A, the source refers to the window of domain A, which can be used for bidirectional communication.

Example:


Alright, finally we can give an example (Wait, where's my candied chestnut?).

Example Page:

http://jsbin.com/wecoqi

Example Code:

http://jsbin.com/wecoqi/9/edit?html,js

http://jsbin.com/qetuwicebo/9/edit?html,js

Code Explanation

The user opens page A, clicks the Open Window button to open a new page B (due to limited resources, the demo uses the same domain for demonstration). Then they return to page A and click the push message button to send a hello to page B, while also receiving feedback from page B. Going back to page B, you can see the received message there.

The specific code is as follows.

Page A

// Get button and display text DOM
var openWindow = document.getElementById('open');
var pushMessage = document.getElementById('push');
var messageBox = document.getElementById('message');

var newWin;

// Open Window button event
openWindow.addEventListener('click',function(){
    // After clicking, open a new window and get a reference to it
      newWin = window.open('http://jsbin.com/qetuwicebo');
})

pushMessage.addEventListener('click',function(){
    // Click the send message button to send hello to the new window
    // Note that the second parameter is the domain receiving the message, although * can match all domains,
    // in production, it is strongly recommended to use the real domain to prevent unnecessary attacks.
    newWin.postMessage('你好','*');
    //
    messageBox.innerHTML=  messageBox.innerHTML+'Sent the message "你好", please check the new opened page for the message received.'
})

// Listen to the message event to receive information from other pages.
window.addEventListener('message',function(event){
  messageBox.innerHTML=  messageBox.innerHTML+'<br>Received response: '+event.data
})

Page B

// Listen to message event
window.addEventListener("message", receiveMessage, false);

function receiveMessage(event ){  
    // Note, in production, always verify event.origin to avoid potential security issues.
      var html='event.data: '+event.data+'<br>';
      html += 'event.origin: '+event.origin+'<br>';
      html += 'event.source: '+event.source+'<br>';
      document.getElementById('message').innerHTML= html;

      // After receiving the message, we will send a reply to the parent page.
      // event.source can be used to obtain a reference to the originating page.
      event.source.postMessage('Hi, I am from the newly opened page, I received your posted message.',event.origin);
}

Conclusion

I don't want to write a conclusion, but if I don't, @Robin Ma will say that my article's ending is too abrupt. Alright, here's the conclusion, that's it. By the way, remember to reply, this is the best encouragement ~ :)

THE END

More Articles You Might Be Interested In

Did this post inspire any ideas? Share your thoughts in the comments!

avatar

Mofei's Friend (Click to edit)

Give me some inspiration!

HI. I AM MOFEI!

NICE TO MEET YOU!