About PostMessage
Window.postmessage is a HTML5 function, but support ie8+, if your site does not need to support IE6 and IE7, then you can use Window.postmessage. About Window.postmessage, a lot of friends say he can support Cross-domain, yes, Window.postmessage is the direct data transfer between client and client, which can be passed across domain or same domain.
Application ScenariosI just give a simple application scenario, of course, this feature can be used in many places. If you have a page, the page to get some of the user information, click to enter another page, the other page default is not to get the user information, you can through the window.postmessage part of the user information uploaded to this page. (Of course, you have to consider security and so on.) ) Code example
send a message:Pop up a new window var domain = "http://haorooms.com"; var mypopup = window.open (domain + "/windowpostmessagelistener.html", "Mywindow"); Periodic send Message settimeout (function () {//var messages = "Current time is" + (new Date (). GetTime ()); var message = {Name: "site", Sex: "Male"}; You can also pass some data here, obj et console.log ("The data passed is" + message); Mypopup.postmessage (Message,domain); },1000); To delay, we generally use the timer settimeout delay and reuse.
accepted pagesListen for message feedback Window.addeventlistener ("Messages", function (event) {if (Event.origin!== "http://haorooms.com") return;//This sentence Break It is not i this domain name jumps over the Console.log ("Received response:", event.data);},false);
The following figure, accept the page to get the data
If you are using an IFRAME, the code should write this:Capture iframe var domain = "http://haorooms.com"; var iframe = document.getElementById ("Myiframe"). Contentwindow; Send Message settimeout (function () {//var messages = "Current time is" + (new Date (). GetTime ()); var message = {Name: "site", Sex: "Male"}; You can also pass some data here, obj et console.log ("The data passed is:" + message); Send the message and target URI iframe.postmessage (Message,domain); },1000); Accept data//Response event Window.addeventlistener ("Message", function (event) {if (Event.origin!== "http://haorooms.com") return; Console.log ("Message Received:" + event.data,event); Event.source.postMessage ("Holla Back youngin!", event.origin); },false); The code snippet above is a feedback message to the source, and the confirmation message has been received. Here are some of the more important event properties: The source– message source, the sending window for the message/iframe. origin– The URI of the message source, which may contain protocols, domain names, and ports, to validate the data source. data– sends the data way sent to the receiving party.