Home >
Article > Web Front-end > js communication between iframe subpage and parent page in the same domain or different domains_javascript skills
js communication between iframe subpage and parent page in the same domain or different domains_javascript skills
WBOYOriginal
2016-05-16 16:49:381144browse
The communication methods between the iframe subpage and the parent page are different depending on whether the src attribute in the iframe is a same-domain link or a cross-domain link.
1. Communication between parent and child pages in the same domain
The parent page calls the child page method: FrameName.window.childMethod();
The child page calls the parent page method: parent.window.parentMethod(); DOM element access
After obtaining the window.document object of the page, you can access the DOM element Notes
Be sure to operate after the iframe is loaded. If the iframe is still If you start calling methods or variables before loading is complete, an error will occur. There are two ways to determine whether the iframe has been loaded:
1. Use the onload event on the iframe
2. Use document.readyState=="complete" to determine
2. Cross-domain parent-child page communication method
If the iframe is linked to an external page, the communication method under the same domain name cannot be used because of the security mechanism. The parent page passes data to the child page
The trick is to use the hash value of the location object and pass the communication data through it. Just add an additional data string after the src of the iframe in the parent page, and then use some method to instantly obtain the data here in the sub-page, for example:
1. Pass in the sub-page The setInterval method sets the timer and monitors changes in location.href to obtain the above data information
2. Then the child page performs corresponding logical processing based on this data information
The child page reports to the parent page The technique for passing data
is to use a proxy iframe, which is embedded in the child page and must remain in the same domain as the parent page, and then fully utilizes the implementation principle of the first communication method above to transfer the child page. The data of the page is passed to the proxy iframe, and since the proxy iframe and the main page are in the same domain, the main page can obtain the data using the same domain method. Use window.top or window.parent.parent to get a reference to the top-level window object in the browser.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn