I believe that many partners in the project will encounter the need to embed external chain page situation, at this time is likely to encounter a problem, is how to iframe sub-page between their own project pages, especially cross-domain situation

1. Sympatric case

1.1 Obtaining DOM elements from each other

1.1.1 Obtaining the DOM element of the child page from the parent page

// Select * from the dom element in the document where the iframe is located;

document.getElementById('iframe').contentWindow.document.getElementById('domId');
Copy the code

1.1.2 Child Page Gets the DOM element of the parent page

// window.parent returns to the parent page

window.parent.document.getElementById('domid');
Copy the code

1.2 Call methods to each other

The parent page calls the child page method:

iframeName.window.childMethod();
Copy the code

The child page calls the parent page method:

parent.window.parentMethod();
Copy the code

1.3 Call variables to each other

Parent page access child page variable:

Document.getelementbyid ('iframe').name(child page variable name);Copy the code

Child page access parent page variable:

Parent. Name (parent page variable name);Copy the code

2. Cross-domain situations

Codomain case is relatively simple, mainly talk about the cross-domain case of the scheme, generally there are two solutions. One is to create a proxy page and pass values through the proxy page. The other is through H5’s postMessage method.

Here’s the second option, using the VUE project as an example

2.1 Child pages transmit values to parent pages

Vue parent page

Created () {window.addeventListener ('message', e => {console.log(e.data); })}Copy the code

The iframe child pages

/ / the first parameter data for the transmission of data, the second parameter can be designated to receive the source document. The getElementById (" iframe "). ContentWindow. PostMessage (data, '*')Copy the code

2.2 The parent page sends data to the child page

Vue parent page

/ / note: So vUE needs to be in Mounted, // getElementById mounted() {// getElementById = this.$refs.iframe const iframe = this.$refs.iframe iframe.contentWindow.postMessage(data,'*') }Copy the code

The iframe child pages

Window.addeventlistener ('message', e => {// e.ata sends data to the parent page console.log(e.ata); })Copy the code

2.3 Security optimization can also be done

All the above receiving sources use ‘*’, that is, the IP address of the receiving source is not limited. For security reasons, you can use the following method to optimize the port

The sender:

The postMessage method specifies a second argument, such as www.baidu.com

Receiver:

Listen for the message callback and use e.olin to determine the source of the message