chrome中iframe交互问题

时间:2021-10-30 21:12:27

环境: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 onclick="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 onload="OnLoad()">
<button onclick="modiframe()">改值</button>
</body>
</html>

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

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

1.html5的postMessage

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