如何选择性地显示Chrome扩展'的工具栏图标

How do I selectively display a Chrome Extension's toolbar icon?

本文关键字:工具栏 图标 扩展 选择性 显示 Chrome      更新时间:2023-09-26

我有一个带背景页的chrome扩展。background.js脚本仅在某些网站上正确运行(如预期)。如何在没有使用图标的网站上隐藏谷歌chrome工具栏中的图标?优选地,仅在允许的情况下在清单中定义的站点上显示图标。

我正在尝试使用pageActions,这是我当前无法运行的代码。没有显示任何图标。

// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Called when the url of a tab changes.
function checkForValidUrl(tabId, changeInfo, tab) {
// If the tabs url starts with "http://specificsite.com"...
if (tab.url.indexOf('http://') == 0) {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);

舱单:

  "page_action": {
        "default_icon": "key.png",
        "default_title": "Download this Deck"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },

编辑:在我重新加载扩展后,它似乎可以工作,直到我用以下代码切换选项卡:

chrome.tabs.getSelected(null, function(tab) {
    chrome.pageAction.show(tab.id);
});

有一个特定的API来匹配您的案例,declarativeContent API。

当前实现的唯一可能的操作是根据一组规则显示"页面操作"按钮。有关更广泛的示例,请参阅文档。

chrome.runtime.onInstalled.addListener(function(details) {
  var rule = {
    conditions: [
      new chrome.declarativeContent.PageStateMatcher({
        pageUrl: { hostSuffix: 'example.com' },
      })
    ],
    actions: [ new chrome.declarativeContent.ShowPageAction() ]
  };
  chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
    chrome.declarativeContent.onPageChanged.addRules([rule]);
  });
});

您应该为此使用页面操作,而不是浏览器操作。它是专门为你的要求而设计的。

https://developer.chrome.com/extensions/pageAction