Due to the limitations of homologous policies, cross-domain communication has always been a difficult problem. Of course there are many solutions:
1. The settings of document.domain+iframe are applied to the main domain and the subdomain are different;
2. Using iframe and location.hash, the data is directly exposed to the url, and the data capacity and type are limited.
3.Flash LocalConnection, objects can communicate in one SWF file or between multiple SWF files, as long as
Just be on the same client, cross-applications, and cross-domain.
window.name saves data and cross-domain iframe static proxy dynamic transmission scheme, fully utilizes the feature of window.name that does not change due to page url changes.
There are many example codes on the Internet, you can search for them yourself.
One of the coolest APIs in html5: Cross Document Messaging. Advanced browsers Internet Explorer 8+, chrome, Firefox, Opera and Safari will all support this feature. This function is also very simple to implement, mainly including the "message" event that accepts information and the "postMessage" method that sends messages.
The "postMessage" method to send a message
Send a message to the outside window:
The code copy is as follows: otherWindow.postMessage(message, targetOrigin);
otherWindow: refers to the target window, that is, which window is sent to, it is a member of the window.frames attribute or a window created by the window.open method
Parameter description:
1.message: It is the message to be sent, the type is String, Object (not supported by IE8, 9)
2.targetOrigin: It is a limited message receiving range, and you do not restrict it. Please use '*'
"message" event that accepts information
The code copy is as follows:
var onmessage = function (event) {
var data = event.data;
var origin = event.origin;
//do someing
};
if (typeof window.addEventListener != 'undefined') {
window.addEventListener('message', onmessage, false);
} else if (typeof window.attachEvent != 'undefined') {
//for ie
window.attachEvent('onmessage', onmessage);
}
The first parameter of the callback function receives the Event object and has three common properties:
1.data: Message
2.origin: Source address
3.source: Source DOMWindow object
Of course, postmessage also has some shortcomings:
1. The data type values passed under ie8 and ie9 support string types, but you can use mutual conversion between JSON objects and strings to solve this problem;
2.ie6, ie7 needs to write a compatibility plan. I personally think window.name is more reliable;