谷歌浏览器无法接受.contentDocument或.contentWindow

3
当我尝试运行我的代码时: Testing.html -测试.html
<script language="JavaScript" type="text/javascript">
function find() { 
var iframeEl = document.getElementById('love');
if ( iframeEl.contentDocument ) {
    var form = iframeEl.contentDocument.document.getElementById('hi').getAttribute('href');
    alert(form)
} else if ( iframeEl.contentWindow ) {
    var form = iframeEl.contentWindow.document.getElementById('hi').getAttribute('href');
    alert(form)
} 
  }
</script>
<body onload="find()">
<iframe name="lovez" src="frame.html" id="love"><a href="http://www.google.com" id="hi">Testingz</a></iframe>
</body>

Frame.html -

<a href="http://www.google.com" id="hi">Testing</a>

该代码不会触发警告框。但在Internet Explorer中会触发。我在网上搜索了很多例子,尝试了所有的代码,却找不到一个能在Google Chrome中正常运行的简单示例。我是做错了什么还是只有Google Chrome不能运行这个代码?

3个回答

6
我注意到无论是contentDocument还是getSVGDocument(用于来自svg文件的svg对象),如果代码来自Web服务器,则可以正常工作,但是当我将代码复制到本地文件时,它将无法工作。 这里有一个示例链接,其中包含一段我从中复制的代码,在Web上可以工作,但是从我的磁盘上不行。 这是我刚刚从Chrome中找到的解决方案(感谢Artem S),即使用--allow-file-access-from-files标志。

注意:上面链接中的解决方案在引号内包含了标志。这给我带来了错误。当我将标志放在引号外时,它最终起作用了。 - Max Starkenburg

1

尝试不使用.document

var form = iframeEl.contentDocument.getElementById('hi').getAttribute('href');

替代

var form = iframeEl.contentDocument.document.getElementById('hi').getAttribute('href');

通过调试器,我可以看到iframe已经在屏幕上了,但是contentWindow和contentDocument属性都是未定义的。 - Howard M. Lewis Ship

0

@IsraelGav的回答在某种意义上是正确的,当代码从本地文件访问时会出现这个问题,但从Web服务器访问时则不会。他还指出使用--allow-file-access-from-files标志可以允许Chrome访问本地文件。

然而,它忽略了一个重要的安全问题。这个问题以及另一种可能的解决方案最初在@orszaczky的其他SO回答中描述。总结替代解决方案:在Windows上,安装http-server(npm install -g http-server),然后从项目目录运行http-server。在Mac/Linux上,从本地目录运行python -m SimpleHttpServer。现在您可以在浏览器中访问本地托管的网站。在Windows上,我必须使用localhost:8080,而在Mac上,我必须使用localhost:8000

顺便说一下,这不仅是Chrome(v49.0)的问题,也是Opera(v35.0)的问题,无论是在Windows还是Mac上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接