Because front-end javascript imposes security restrictions on cross-origin access, javascript can only access content under the same domain name as the document containing it. Next, this article introduces the encapsulation of iframe cross-origin communication.
Iframe cross-origin Communication
View demo source code download
As we all know, because front-end javascript imposes security restrictions on cross-origin access, javascript can only access content in the same domain as the document containing it.
Example:
The requirement is that.
1. Create a cube for internal pages on the top page
The Code is as follows:
Function testFun (text ){
Alert (text );
}
2. Insert IFRAME in http://www.demo.org/top.html
The Code is as follows:
3. Create a proxy page at www.demo.org at http://www.demo.org/proxy.htmlfor cross-domain communication.
4. Add the proxy page logic at http://www.demo.org/proxy.html.
5. Access the JS configuration proxy address on the http://www.iframe.com/iframe.html page.
The Code is as follows:
TopProxyConfig = {url: 'http: // www.demo.org/proxy.html'workflow '};
6. Load the communication module through kissy
The Code is as follows:
KISSY. use ('topproxy', function (S, topproxy ){
// Execute the code
});
7.
KISSY. use ('topproxy', function (S, topproxy) {TopProxy. call ('testfun', 'This is a real story ');});
The first parameter of the call method is the Global Method Name of the external webpage. "." is supported, and the following parameters are infinite and are uploaded to the target method.
Note:
1. It may not be executed immediately after the call. It will not be triggered until the iframe is loaded. If you want to pre-load, You can execute a useless method in advance.
2. If TopProxyConfig is not set, the system considers that the reference iframe and the parent iframe are in the same domain (large domain) and directly calls the top object.
3. In IE678, an error may occur when you directly call the system method in top, because the system method does not support apply.
Principle:
Page A is embedded into the iframe page B of the day, where B wants to call the method of A and pass data, then A iframe Page C in the same domain of page A can be embedded in B, c. You can use window. top to access the window of. In B, we can change the href hash of C to pass some information to C, and then C will pass the information to A, so as to indirectly transfer the information to.