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

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

<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的

二、或者通过修改哈希值触发子页面或父页面方法;
父页面:

<body onhashchange="alert('test.html hash change')">
	<input type="button" value="test" onclick="document.getElementById('tt').src = 'http://test2.com/test2.html#bbb'">
	<iframe src="http://test2.com/test2.html" id="tt"></iframe>
</body>

子页面:

<body onhashchange="alert('test2.html hash change')">
	<input type="button" value="test2" onclick="top.location='http://test.com/test.html#aaa'">
</body>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值