Chrome 内容脚本在给定标签页的所有网页中运行

Chrome content script run in all pages in a given tab

本文关键字:网页 运行 标签 脚本 Chrome      更新时间:2023-09-26

我有一个带有弹出窗口的Chrome扩展程序(内容脚本)。当用户单击弹出窗口中的"开始"按钮时,我希望打开一个新选项卡以访问URL(例如 www.test.com),并将内容脚本注入该选项卡。不仅执行一次,而且注入,以便它在同一选项卡上的 (www.test.com/*) 上工作。不是在其他选项卡中 - 只是那个。

这是我现在拥有的:

chrome.tabs.create({
        'url': 'http://test.com/shop/new'
        }, function(tab) {
        chrome.tabs.executeScript(tab.id, {
            'file': 'script.js'
        });
    });

但是,正在使用chrome.tabs.executeScript,它只执行一次脚本。该脚本将页面重定向到"http://test.com/shop/new/xxx",但由于脚本只执行一次,因此当页面更改时它会停止工作。再次 - 我怎样才能使脚本注入到该选项卡中的所有"http://test.com/shop/*"页面中?

一个好主意是创建一个始终注入到http://test.com/shop/*中的脚本(通过清单):

  "content_scripts" : [
    {
      matches: ["http://test.com/shop/*"],
      js: ["script.js"]
    }
  ],

然后,在脚本中,询问后台页面是否应为此 ID 处于活动状态:

// script.js
chrome.runtime.sendMessage({shouldIRun : true}, function(response){
  if(response) {
    // Actually do stuff
  }
});

在后台脚本中,记录您希望它应用于的选项卡:

// Background script
var activeTabs = {}; // Slightly more difficult with event pages
// At some point when you enable it, e.g. in a browserAction.onClicked listener
activeTabs[tabId] = true;
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
  if(message.shouldIRun) {
    // Double negation to ensure true/false
    sendResponse(!!activeTabs[sender.tab.id]);
  }
});
// It's a good idea to clear the stray entries
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
  delete activeTabs[tabId];
});
// Sometimes this can also happen
chrome.tabs.onReplaced.addListener(function(addedTabId, removedTabId) {
  if(!!activeTabs[removedTabId]) activeTabs[addedTabId] = true;
  delete activeTabs[removedTabId];
});