Chrome 扩展 - 每个页面加载时都会多次注入内容脚本
我在 Chrome 扩展程序中多次将内容脚本注入同一页面时遇到一些问题。
我从“background.html”页面注入内容脚本,在选项卡更改上:
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
chrome.tabs.getSelected(null,function(tab){
// Do some stuff
chrome.tabs.executeScript(null, { code: code}, function(result){
...等
在内容脚本内,我有一些 console.log 命令
问题是,当我加载单个页面时,我看到每个的日志在控制台中显示 2-4 次。
我很清楚,这是由于页面内的 iframe 造成的,我认为至少......我的问题是为什么?
我在文档中看到“all_frames”(清单中的内容脚本权限数组)默认应设置为“false”,导致内容脚本仅被注入到页面的顶部框架,但这根本没有发生!
为什么要多次注射?我需要将“all_frames”物理设置为 false 吗?
其次:
有什么方法可以判断扩展程序尝试注入内容脚本的页面是 iframe 还是“background.html”页面中的顶部?
我尝试过
if(window.top === window){ console.log('whatever'); }
,发现它并不是 100% 有效。即使我在代码块的其余部分(围绕 chrome.tabs.executeScript() )有这个条件,我仍然看到多次注入内容脚本......
任何想法或建议将不胜感激! :)
I'm having some issues with a content script being injected to the same page multiple times in my Chrome extension.
I am injecting the content script from my "background.html" page, on Tab change:
chrome.tabs.onUpdated.addListener(function(tabId,changeInfo,tab){
chrome.tabs.getSelected(null,function(tab){
// Do some stuff
chrome.tabs.executeScript(null, { code: code}, function(result){
...etc
Inside the content script, I have some console.log commands
The problem is that when I load a SINGLE page, I am seeing each of the logs show up in the console 2-4 times.
It's pretty clear to me that this is happening because of iframes within the page, I think at least... My question is WHY?
I have seen in the documentation that "all_frames" (content script permissions array in manifest) should be set to "false" by default, resulting in the content script only being injected to the top frame of the page, but this is simply not happening!
Why is it being injected multiple times? Do I need to physically set "all_frames" to false?
Secondly:
Is there any way to tell if the page that the extension is trying to inject the content script to is an iframe or top from WITHIN the "background.html" page?
I have tried
if(window.top === window){ console.log('whatever'); }
And found that it does NOT work 100% of the time. Even when I have that conditional around the rest of my code block (around chrome.tabs.executeScript() ), I am still seeing the content script injected multiple times....
Any ideas or suggestions would be greatly appreciated! :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
onUpdated
每次打开标签页时都会触发状态变化。这包括何时加载和完成加载,这解释了许多日志语句。每次事件触发时,您都需要检查发生了什么变化(URL 更改、加载等)。
onUpdated
fires each time a tab's state changes. This includes when it is loading and done loading, which explains the many log statements.You need to check for what changed (the URL changed, it loaded, etc.) each time the event fires.