Comment: window.postMessage allows multiple windows/frames to pass data and information across domains. Here is a description of how window.postMessage works and how to use it in FireFox, IE8+, Opera, Safari and Chrome
Original address: HTML5's window.postMessage APIOnline example: Using HTML5's window.postMessage (please open the console to view the log)
I wrote a MooTools plugin PostMessager to encapsulate window.postMessage, you can click here to download it!
Not many people know about the HTML5 window.postMessage interface API. window.postMessage allows data and information to be passed across domains between multiple windows/frames. In essence, window.postMessage plays a role of cross-domain Ajax requests, and of course, it does not require a remote server to collaborate. Next, we will introduce how window.postMessage works, and how to use it in FireFox, IE8+, Opera, Safari, and Chrome.
1. Message sending end
The first step in the whole process is to set up a message source. Through this message source, we can send window-level data (messages) to the newly opened window (or iframe). In the following example, the frequency of sending messages to a new window is once every 6 seconds, and event listening is set to process the response information returned by the target window.
function trace(message){
var infos = Array.prototype.slice.call(arguments,0).join(" ");
if("console" in window){
console.log(infos);
} else {
alert(infos);
}
};
// Create pop-up window
var domain = 'http://scriptandstyle.com';
var myPopup = window.open(domain + '/windowPostMessageListener.html','myWindow');
// Send messages regularly
setInterval(function(){
var message = 'Current time: ' + (new Date().getTime());
trace('Data source. Message sent: ' + message);
myPopup.postMessage(message,domain); //Send data information and set the target URI
},6*1000);
function bindEvent(target,noOnEventName,handler){
if(window.addEventListener){
target.addEventListener(noOnEventName,handler);
} else if(window.attachEvent){
// The listening setting function of IE is attachEvent
target.attachEvent("on"+noOnEventName,handler);
} else {
target["on"+noOnEventName]=handler;
}
};
// Listen to the received information.
bindEvent(window,'message',function(event) {
// Only receive messages from specific domains
if(event.origin !== 'http://scriptandstyle.com') return;
trace('Response information received: ',event.data);
},false);
The original author used the window.addEventListener method to bind events, but an error will be reported under IE (IE is window.attachEvent). Of course, you can create functions to wrap events, or use ready-made class libraries, such as MooTools or jQuery/dojo to implement them.
In the example above, if the new window opens normally, we can send a message through the reference to myPopup of the window object and specify the URI (protocol, hostname, port number) that must be matched (if the user jumps to another page in the child window, the message will not be sent).
Similarly, we also bind the event handler to receive message messages. Here is a reminder that it is important to verify the origin attribute of the message event, because it may receive messages sent to you by all URIs, so that it will not be confused when multiple frames interact. After verifying origin, how to process this message depends on your specific business and needs.
If using an iframe, the code is as follows:
// Create another window (iframe,frame,frameset,top,window and other objects that belong to window-related.)
var domain = 'http://scriptandstyle.com';
var iframe = document.getElementById('myIFrame').contentWindow;
// Send messages in a loop, of course, event-driven or something like that can be used. . .
setInterval(function(){
var message = 'Current time: ' + (new Date().getTime());
trace('Data source. Message sent: ' + message);
iframe.postMessage(message,domain); //Send data information and set the target URI
},6*1000);
Make sure to access the contentWindow property of the iframe object - not just the iframe object.
2. Message receiver
The second step in the entire process is to make the target window ready. What the purpose window needs to do is to listen to the message event, and of course it also needs to verify the origin source of the event. Again, the message event handler can accept messages sent to him by any domain name, so it is very important to verify origin and only handle messages that only trust lists.
// Listen to the received information.
bindEvent(window,'message',function(event) {
// Only receive messages from specific domains
if(event.origin !== 'http://davidwalsh.name') return;
trace('listen to information: ',event.data);
// Reply to the message
event.source.postMessage("Hello, friends, I have received the message, event.origin);
},false);
The above example responds to the requesting party.
The important attributes of the message event are:
source - send message window/iframe object
origin - corresponding to the URI (protocol, domain, and port, if specified)
data - specific data information
These three objects are essential for the message system and verification.
Notes on using window.postMessage
Just like all other web technologies, the danger is obvious if used improperly (no verification of event sources). Of course, safety is guaranteed by you.
window.postMessage is very similar to PHP in JavaScript technology (haha, small advertisement!).window.postMessage is a cool technology, what do you think?