在后台脚本中,监听新打开的选项卡 [英] In background script, listen for newly opened tab

查看:115
本文介绍了在后台脚本中,监听新打开的选项卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的后台脚本或任何地方,但内容脚本中,我试图监听活动选项卡或新打开的选项卡。



我有这个,但这显然是不正确的:



< img src =https://i.stack.imgur.com/42h03.pngalt =在这里输入图片描述>



我的我试图做的是将一个内容脚本注入到活动选项卡中。我不希望我的内容脚本针对每个标签页/窗口运行,仅针对选择标签。



有人知道如何为某些标签插入内容脚本吗?我无法弄清楚。我假设注入内容脚本的最好方法是来自后台脚本。

解决方案

如果您想在已激活的代码中运行代码( chrome.tabs.query ):

  chrome.tabs.query({active:true,currentWindow:true},function(foundTabs){
const activeTabId = foundTabs [0] .id;

chrome.tabs.executeScript(activeTabId,{
file:'inject.js'
});
} )

如果您想将文件注入每个新激活的选项卡( chrome.tabs.onActivated ):



  chrome.tabs.onActivated.addListener(function(activeInfo){
chrome.tabs.executeScript(activeInfo.tabId,{
file :'inject.js'
});
});

请务必检查您是否已经注入了该文件,以防止多次注入。

对于这两种情况,权限应该包含标签

In my background script, or anywhere but a content script, I am trying to listen for the active tab, or a newly opened tab.

I have this, but this is apparently incorrect:

What I am trying to do is to inject a content-script into the active tab. I don't want my content script to run for every tab/window, just for select tabs.

Does anyone know how to inject a content script for certain tabs? I can't figure it out. I assume the best way to inject content scripts is from the background script.

解决方案

If you want to run a code in already activated tab (chrome.tabs.query):

chrome.tabs.query({active: true, currentWindow: true}, function(foundTabs) {
    const activeTabId = foundTabs[0].id;

    chrome.tabs.executeScript(activeTabId, {
      file: 'inject.js'
    }); 
})

In case you want to inject a file into every newly activated tab (chrome.tabs.onActivated):

chrome.tabs.onActivated.addListener(function(activeInfo) {
    chrome.tabs.executeScript(activeInfo.tabId, {
        file: 'inject.js'
    }); 
});

Be sure to check if you have injected the file already, in order to prevent multiple injections.

For both cases, permissions should include tabs.

这篇关于在后台脚本中,监听新打开的选项卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆