我有一个带有背景页面的 Chrome 扩展。 background.js 脚本仅在某些站点上正确运行(按预期)。如何在不使用该图标的网站上隐藏 google 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]);
});
});
看起来使用这个答案
中提到的声明内容不再可能了不幸的是,这是不可能的(不再)。无论是否是声明性内容,地址栏附近是否存在扩展程序图标仅由用户通过从扩展程序菜单中固定/取消固定来决定。在旧版本的 Chrome 中,使用 chrome.pageAction 会导致扩展程序图标仅显示在清单中声明的匹配网站的地址栏中。然而,不久前事情发生了变化...