简体   繁体   English

我无法在 Chrome 中获取 iframe 元素

[英]I can't get iframe elements in Chrome

I'm trying to get an element in an iframe with contentWindow.document (or contentDocument).我正在尝试使用 contentWindow.document(或 contentDocument)在 iframe 中获取元素。

I was able to get information without problems with FireFox and Chrome version 99 or earlier, but suddenly I can not get information with Chrome version 100 or later.使用 FireFox 和 Chrome 版本 99 或更早版本时,我能够毫无问题地获取信息,但突然间我无法使用 Chrome 版本 100 或更高版本获取信息。

Also, I'm not sure if it's related, but this phenomenon occurred only in the JS described on the fixed page of Wordpress, and did not occur in the html page that is not Wordpress.另外,我不确定是否有关系,但这种现象只发生在Wordpress的固定页面上描述的JS中,而不是在不是Wordpress的html页面中发生。

The outline of the source is as follows.源的概要如下。

<iframe src="/form/terms/sample.html" width="100%" height="500px" frameborder="0" id="iframe"></iframe>
<script>
window.onload = function(){
    var iframe = document.getElementById("iframe");
    var iframe_doc = iframe.contentDocument || iframe.contentWindow.document;
    console.log(iframe_doc);
}
</script>

The result is below, the body element is empty.结果如下,body 元素为空。

<html>
    <head></head>
    <body></body>
</html>

The version of Wordpress is 5.7.6. Wordpress 的版本是 5.7.6。

Do you know the cause?你知道原因吗?

Tested on Firefox v102, got following error: Uncaught DOMException: Permission denied to access property "document" on cross-origin object在 Firefox v102 上测试,出现以下错误: Uncaught DOMException: Permission denied to access property "document" on cross-origin object

The err happens if you process it on the website starts load.如果您在网站上处理它开始加载,则会发生错误。

First add a <meta> tag in <head> :首先在<head>中添加一个<meta>标签:

<meta name="referer" content="access-control-allow-origin"/>

Then edit the JavaScript code:然后编辑 JavaScript 代码:

(function() {
    var iframe = document.getElementById("iframe");
    var iframe_doc = iframe.contentDocument || iframe.contentWindow.document;
    console.log(iframe_doc);
})();

Hope this works for you.希望这对你有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM