iframe跨端口报错 Blocked a frame with origin from accessing a cross-origin frame

前言
    在不同的端口号,甚至是不同的ip进行iframe嵌套的时候,在父页面调用子页面的方法的时候,报错

SecurityError: Blocked a frame with origin from accessing a cross-origin frame…

问题原因
    在不同端口号下,不能使用传统的iframe嵌套调用方法。

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


    因为

    同源安全策略
        你不能用javascript访问一个<iframe>,如果你能做到这一点,那将是一个巨大的安全缺陷。对于同一源策略浏览器,阻止脚本尝试访问具有不同源的帧。

        如果地址中至少有一个部分未保留,则认为来源不同:

<protocol>://<hostname>:<port>/path/to/page.html


    如果要访问iframe,协议、主机名和端口必须与域相同。

Examples
    下面是尝试访问以下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



解决方法
    尽管同一源站策略阻止脚本访问不同源站的内容,但如果您同时拥有这两个页面,则可以使用window.postmessageand其相关消息事件在两个页面之间发送消息来解决此问题。

//在主页面
var frame = document.getElementById('your-frame-id'); 
frame.contentWindow. postMessage (data, '*');

data可以是string,boolean,number,array,object

//在iframe子页面
window. addEventListener ('message', function(event) { 
    //event.data获取传过来的数据
});

注意:父页面的postMessage是触发addEventListener的

原文地址:https://www.cnblogs.com/Tohold/p/10690167.html