Tag Archives: Blocked a frame with origin from accessing a cross-origin frame

Iframe Cross-port Blocked a frame with origin from accessing a cross-origin frame

Foreword
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…

The reason for the problem is that the traditional iframe nested call method cannot be used under different port numbers

document.getElementById("mainFrame").contentWindow.xxxx();

because

Homologous security policy
you cannot access a & lt; iframe>, If you can do that, it’s going to 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 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

solution
although the same origin policy prevents scripts from accessing the content of different origin sites, if you have these two pages at the same time, you can use window.postmessageand its related message events to send messages between the two pages to solve this problem

var frame = document.getElementById('your-frame-id'); 
frame.contentWindow. postMessage (data, '*');

data may 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 addeventlistener