chrome中iframe交互问题

环境:ie11,chrome43

parent.html

<html>
<head>
<script type="text/javascript">
function modiframe()
{
	var ifr_doc = document.getElementById("iframe1").contentDocument;
	ifr_doc.getElementById("label1").innerHTML = "改变了";
}
</script>
</head>
<body>
<button οnclick="modiframe()">改值</button>
<iframe id="iframe1" src="a.html"></iframe>
</body>
</html>

a.html

<html>
<body>
<label id="label1">child</label>
</body>
</html>

本地测试,在parent.html中点击按钮,在ie11和firefox39都有效果,

chrome报错:

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "null" from accessing a frame with origin "null". Protocols, domains, and ports must match.

错误行代码:

var ifr_doc = document.getElementById("iframe1").contentDocument;

原因:跨域,file:///类型的也算跨域,chrome对于file协议有安全限制,无法用js访问本地资源,对于http则是好的,所以上面页面要是在iis/apache网站中打开应该是没问题的

参考:http://bbs.csdn.net/topics/390894709

http://my.oschina.net/freax/blog/305164?p=1

http://bbs.csdn.net/topics/390910056

解决:

因为我的子页面较小,故直接动态创建iframe元素,不使用a.html

parent.html

<html>
<head>
<script type="text/javascript">
    var ifr_doc;
    function OnLoad() {
        var iframe = document.createElement('iframe');
        var ifr = document.body.appendChild(iframe);
        ifr_doc = ifr.contentWindow.document;

        ifr.frameborder = '1px';
        ifr.height = '100px';
        ifr.width = '100px';
        ifr.style.display = 'inline';

        var loadjs = '<html><body><label id=\"label1\">child</label></body></html>';

        ifr_doc.open();
        ifr_doc.write(loadjs);
        ifr_doc.close();
    }
    function modiframe() {
        ifr_doc.getElementById("label1").innerHTML = "改变了";
    }
</script>
</head>
<body οnlοad="OnLoad()">
<button οnclick="modiframe()">改值</button>
</body>
</html>

参考:http://www.xuebuyuan.com/286558.html

除此之外,还有两种技术解决chrome的iframe加载问题,但我没试

1.html5的postMessage

2.在网站中部署,而非本地打开

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值