Chrome扩展注入脚本仅在标签已许可的情况下

Chrome extension inject script only if tab has permission

我试图通过 chrome.tabs.executeScript 命令注入内容脚本,但它试图注入浏览器上每个打开的选项卡。 在尝试注入脚本之前,是否有一种方法可以确定扩展是否具有选项卡的正确权限(在 manifest.json、permissions 键中)? 我的错误是:Unchecked runtime.lastError: Cannot access contents of url "https://exmaple.com/". Extension manifest must request permission to access this host.

我的代码是:

 const chromeManifest = chrome.runtime.getManifest();
 chrome.tabs.query({}, tabs => {
    const [script] = chromeManifest?.content_scripts?.[0].js;

    tabs.forEach(tab => {
      /* HERE CHECK IF THERE IS PERMISSION FOR THE TAB */
      chrome.tabs.executeScript(tab.id, {
        file: script,
      });
    });
  });

只需在executeScript的回调中读取chrome.runtime.lastError即可抑制错误。

chrome.tabs.executeScript(tab.id, { file }, () => chrome.runtime.lastError);

作为针对特定站点模式 manifest.json 的 content_scripts 具有 matches 的优化,仅查询与该模式匹配的选项卡。

请注意,<all_urls> 模式也将匹配 chrome://file://chrome-extension:// 选项卡,而 *://*/* 将仅匹配 http://https://.

chrome.runtime.getManifest().content_scripts.forEach(script => {
  const params = {
    runAt: script.run_at,
    allFrames: script.all_frames,
    matchAboutBlank: script.match_about_blank,
  };
  // <all_urls> is not supported here so we use an empty array
  const urlQuery = script.matches.filter(m => m !== '<all_urls>');
  chrome.tabs.query({ url: urlQuery }, tab => {
    script.js.forEach(file => {
      chrome.tabs.executeScript(tab.id, { ...params, file }, () => {
        const err = chrome.runtime.lastError;
        // if (err) console.warn(err.message); 
      });
    });
  });
});