First, the basic principle
HTML5 introduced the cross-document communication API (Cross-document messaging) in order to resolve cross-domain. This API adds a new Window.postmessage method to the Window object, allowing cross-window communication regardless of whether the two windows are of the same origin. This feature is supported by Internet Explorer 8+, Chrome,firefox, opera, and Safari.
Second, the test steps
1. Create a.html
<!DOCTYPE HTML><HTMLLang= "en"><Head> <MetaCharSet= "UTF-8"> <title>Window.postmessage Resolving cross-domain a.html</title></Head><Body><Script>window.onload= function() { varSubwin=window.open ('http://localhost:8081/b.html', 'title'); //The parent window http://localhost:8080/a.html the http://localhost:8081/b.html message to the child window, calling the PostMessage method. Subwin.postmessage ('I'm going to send you a message!', 'http://localhost:8081'); } window.addeventlistener ('message', function(e) {Console.log ('a.html received message:', E.data); });</Script></Body></HTML>
Sends a message and listens for messages.
2. Create b.html
<Script> varMessagefunc= function(event) {if(Event.source!=window.parent) {return; } varData=Event.data,//messageOrigin=Event.origin,//Message Source AddressSource=Event.source;//Source Window Object if(Origin== "http://localhost:8080") {Console.log ('b.html received message:', data); } source.postmessage ('I've already received the message!', origin); }; if (typeofWindow.addeventlistener!= 'undefined') {Window.addeventlistener ('message', Messagefunc,false); } Else if (typeofwindow.attachevent!= 'undefined') {window.attachevent ('message', Messagefunc); }</Script>
3. Open two HTTP servers
4. Open the browser to see the result: http://localhost:8080/a.html
Window.postmessage Resolving cross-domain