When the iframe is nested in different port numbers or even different IP addresses, an error is reported when the parent page calls the method of the child page
SecurityError: Blocked a frame with origin from accessing a cross-origin frame…
Cause of the problem
Under different port numbers, the traditional iframe nested method cannot be used.
document.getElementById("mainFrame").contentWindow.xxxx();
Cause
Homologous security policy
you can’t use JavaScript to access an <iframe>, if you can, it will be a huge security flaw. Prevent scripts from trying to access frames with different sources for the same source policy browser.
If at least one part of the address is not reserved, the source is considered different:
<protocol>://<hostname>:<port>/path/to/page.html
To access an iframe, the protocol, host name, and port must be the same as the domain.
Examples
Here’s what happens when you try to access the following URL
http://www.example.com/home/index.html
URL RESULT
http://www.example.com/home/other.html -> Success
http://www.example.com/dir/inner/another.php -> Success
http://www.example.com:80 -> Success (default port for HTTP)
http://www.example.com:2251 -> Failure: different port
http://data.example.com/dir/other.html -> Failure: different hostname
https://www.example.com/home/index.html.html -> Failure: different protocol
ftp://www.example.com:21 -> Failure: different protocol & port
https://google.com/search?q=james+bond -> Failure: different hostname & protocol
How to Fix
Although the same origin policy prevents scripts from accessing the content of different origin sites, if you have both pages, you can use to window.postmessageand
its related message events send messages between two pages to solve this problem.
On the main page:
var frame = document.getElementById('your-frame-id');
frame.contentWindow. postMessage (data, '*');
data can be string, boolean, number, array, object
In the iframe subpage
window. addEventListener ('message', function(event) {
//event.data gets the data passed to it
});
Note: the PostMessage of the parent page triggers the addeventlistener