Cross-origin communication is always tricky due to the restrictions of the same-origin policy in JavaScript. Of course, there are also many solutions:
1.doc ument. domain + iframe settings apply to the same primary domain but different subdomains;
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, the object can communicate with one or more SWF files in one SWF file, as long
On the same client, cross-application and cross-origin are supported.
Window. name stores data and uses the dynamic transmission scheme of cross-domain iframe static proxy. It fully utilizes the feature that window. name does not change because the page url is changed.
Various solutions have a lot of instance code on the Internet. You can search for them by yourself.
One of the coolest APIs in html5 is Cross-Document message transmission. Advanced browsers such as Internet Explorer 8 +, chrome, Firefox, Opera, and Safari support this function. This function is also very simple, mainly including the "message" event for receiving information and the "postMessage" Method for sending messages.
"PostMessage" Method for sending a message
Send messages to external windows:
Copy codeThe Code is as follows: otherWindow. postMessage (message, targetOrigin );
OtherWindow: refers to the target window, that is, the window to which a message is sent. It is a member of the window. frames attribute or a window created by the window. open method.
Parameter description:
1. message: the message to be sent. The type is String or Object (not supported by IE8 or 9)
2. targetOrigin: Specifies the message receiving range. Use '*' if not '*'
"Message" event for receiving information
Copy codeThe Code 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, which has three common attributes:
1. data: Message
2. origin: Message Source Address
3. source: source DOMWindow object
Of course, postmessage also has some shortcomings:
1. The data type values passed in ie8 and ie9 support the string type. However, you can solve this problem by converting JSON objects and strings;
2. ie6 and ie7 need to write compatible solutions. I personally think window. name is more reliable;