我有一个来自 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 上运行良好.
但是,在某些网站上,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/