chrome浏览器iframe parent.document为undefined

2014-11-05更新:这个问题是由于chrome的同源访问造成的,一般需要发布网站后访问,否则需要给chrome增加启动参数,允许访问本地资源文件。如果你是开发人员,增加chrome的配置是最好的,就不需要再搭建服务器进行访问。

参考:配置chrome支持本地(file协议)ajax请求

 

  chrome浏览器iframe parent.document为undefined,对于window.open打开的页面也一样,不能使用opener对象

  今天测试一个脚本的时候发现,在谷歌chrome浏览器下面,iframe中获取父页的document时竟然为undefined,google chrome神奇了,其他浏览器如ie,firefox没出现这种问题。

  iframe要获取到父页的document对象,需要通过服务器,就是http协议访问时才能获取到,要不直接双击运行【chrome为默认浏览器】或者直接拖进chrome浏览器查看时,iframe使用parent.document得到的是undefined。

  测试代码如下

test.html

<html>
<head></head>
    <body><input type="text" id="txt" />
    <br />
    <iframe src="ifr.html"></iframe></body>
</html>
ifr.html
ifr.html
<input type="button" onclick="setValue()" value="设置父页输入框内容" />
<script>
    function setValue() {
        alert(parent.document)//非http协议访问输出undefined,http协议访问时输出[object HTMLDocument]
        var ipt = parent.document.getElementById('txt');//本地浏览由于parent.document为undefined,所以当然无法使用getElementById方法了
        ipt.value = new Date().toLocaleString();
    }
</script>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:chrome浏览器iframe parent.document为undefined

评论(1)Web开发网
阅读(2257)喜欢(0)JavaScript/Ajax开发技巧