问题描述
我正在关注this example,以便在Chrome扩展程序中启用pageAction
:
// When the extension is installed or upgraded ...
chrome.runtime.onInstalled.addListener(function() {
// Replace all rules ...
chrome.declarativeContent.onPageChanged.removeRules(undefined,function() {
// With a new rule ...
chrome.declarativeContent.onPageChanged.addRules([
{
// That fires when a page's URL contains a 'g' ...
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlContains: 'g' },})
],// And shows the extension's page action.
actions: [ new chrome.declarativeContent.ShowPageAction() ]
}
]);
});
});
我想在生产就绪扩展中实现此功能,但我想了解一件事:为什么使用此行chrome.runtime.onInstalled.addListener
?据我所知,onInstalled将在扩展的更新或安装后仅运行一次,因此可以将其删除并仅使用声明性内容API吗?
解决方法
那是因为declarativeContent规则在内部被记住。
没有chrome.runtime.onInstalled事件,您将在每次后台脚本运行时注册规则,例如,"persistent":false
background script每天可以轻松运行10、100或1000次。重新注册许多规则显然是浪费和缓慢的。