【发布时间】:2020-09-18 09:14:11
【问题描述】:
我正在编写一个 chrome 扩展来操作网站中的 DOM 元素。
我有一个内容脚本似乎被阻止在网页的 iFrame 中执行,即使它已被注入。
content.js:
console.log("this script is executed");
chrome.runtime.sendMessage("Hello background.js, I am a frame");
在网页的控制台和 background.js 的控制台中都只记录第一帧。
起初我认为 iFrame 是动态加载的,因此无法注入内容脚本。
然后我查看了控制台中的JS contexts,似乎情况正好相反:
它们被注入但没有被执行。
我还尝试通过以下方式通过顶部框架访问框架:
let iFrames = document.getElementsByClassName('js-iframe');
for (iFrame of iFrames) {
console.log(iFrame.contentDocument);
console.log(iFrame.contentWindow);
}
//null
//Uncaught (in promise) DOMException: Blocked a frame with origin "https://www.webpage.com" from accessing a cross-origin frame.
我错过了什么?
PS:当然,通过在框架本身中执行的解决方案会更可取,但像我尝试过的解决方法也会非常有帮助。
【问题讨论】:
-
{ "matches": ["https://www.webpage.com/*/*"], "js": ["content.js"], "all_frames": true, "match_about_blank": true, "run_at": "document_start" } -
声明很好,所以唯一的解释是控制台中的grouping of identical messages。
-
感谢您的快速响应,但这不是问题所在。我还向 background.js 发送请求,其中记录了发送者和味精,每个请求都不同。而且也只记录了顶部框架
-
chrome.runtime.onMessage.addListener((msg, sender) => { if (msg === "Hello background.js, I am a frame") { console.log("sender:"); console.log(sender); console.log("msg"); console.log(msg); console.log("-----------------"); } });是否可以动态加载帧?在 chrome 控制台中甚至会有他们的 jsContext 吗? -
后台脚本代码看起来不错。对于 manifest.json 中声明的内容脚本,是否动态创建 iframe 并不重要。 1) 在 devtools 中禁用控制台分组和/或启用时间戳。 2) 在 chrome://extensions 页面点击扩展卡上的重新加载图标,3) 重新加载所有选项卡。
标签: javascript iframe google-chrome-extension content-security-policy content-script