javascript - 从 chrome 扩展插入 iframe 在某些网站上不起作用

标签 javascript html iframe google-chrome-extension content-script

我有一个来自 chrome 扩展的内容脚本,将 iframe 插入到网站中,如下所示。

const mainiframe = document.createElement('iframe')
mainiframe.setAttribute("id", "ext_frame");
mainiframe.style.border = "none"
mainiframe.style.display = "block"
mainiframe.style.position = "fixed"
mainiframe.style.height = "100%";
mainiframe.style.width = "100%";
mainiframe.style.top = "0";
mainiframe.style.left = "0";
mainiframe.style.bottom = "0"
mainiframe.src = chrome.extension.getURL("index.html")
document.body.appendChild(mainiframe)

index.html 只是有一些样板文件。

<html>
  <body>
    Hello World
  </body>
</html>

(index.html 中的内容似乎并不重要)。根据需要在manifest.json中的web_accessible_resources中提到了index.html。

这在大多数网站上效果很好。这里它在 www.google.com 上运行良好.

Here it is working fine on www.google.com The visual result

但是,在某些网站上,iframe 插入根本不起作用。不管做什么。在 www.homedepot.com 上运行相同的代码例如,不会导致 DOM 发生任何变化。我应该在 list 中做些什么来确保它可以插入到任何网站上吗?

最佳答案

感谢wOxxOm's评论,将 iframe 粘贴在封闭的影子根中似乎可以解决问题!对于寻找解决方案而不仅仅是解决方案的其他人:

document.body.appendChild(mainiframe)

我做了一个,

const maindiv = document.createElement('div')
let shadowParent = maindiv.attachShadow({mode:'closed'})
shadowParent.appendChild(mainiframe)
document.body.appendChild(maindiv)

效果非常好!在这种特殊情况下,问题是网站强制删除 iframe。我认为noninertialframe's答案可能也有效,但这需要我重组我的内部应用程序。

关于javascript - 从 chrome 扩展插入 iframe 在某些网站上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67540805/

相关文章:

javascript - ASP.NET - 将数据从我的模型获取到 JavaScript 变量中并使用所述变量填充文本区域

javascript - 如何在没有 document.write 的情况下将 &lt;script&gt; 标签注入(inject)到空 iframe 中?

javascript - 通过循环索引获取数据属性

javascript - 正确答案后脚本中的图像将无法工作

javascript - 未捕获的类型错误说函数不能应用于对象?

html - 带有纯 CSS 的方形 HTML Canvas

html - 在 Bootstrap 上将标题拆分为 2 列(每边 50%)

javascript - 从 webapp 收到消息时如何从 WKWebview 调用 javascript 函数

javascript - Svg : iframe can not delete ! 为什么?

javascript - 如何使用从 iframe 加载的点击事件关闭 Bootstrap 模式