有没有办法为一个网站定义pageAction?我看到了示例,他们都使用background.js
在该文件中显示chrome.pageAction.show(tabId)
。
答案 0 :(得分:1)
要显示特定网站的pageAction,有两种方法。
在特定网站上运行内容脚本,并将消息传递给后台请求页面操作:
// contentscript.js
chrome.extension.sendMessage('showPageAction');
// background.js
chrome.extension.onMessage.addListener(function(message, sender) {
if (message == 'showPageAction') {
chrome.pageAction.show(sender.tab.id);
}
});
manifest.json
的一部分:
"content_scripts": [{
"js": ["contentscript.js"],
"run_at": "document_start",
"matches": ["http://example.com/"]
}]
matches
的有效值已在文档match patterns中准确定义
请注意,此示例中的匹配模式与http://example.com/
匹配,而不是http://example.com/index.html
。如果您想匹配网站上的任何内容,请使用http://example.com/*
(附加星号)。
chrome.tabs
API 如果您不想使用内容脚本,可以使用chrome.tabs
个事件来显示页面操作:
// background.js
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
if (changeInfo.url == 'http://example.com/') {
chrome.pageAction.show(tabId);
}
});
除非您已使用chrome.tabs
API,否则我建议使用内容脚本方法。为什么?如果您在清单文件中请求"tabs"
权限,则您的用户将在安装时看到以下警告:
安装
<name of your extension>
?
它可以访问:
访问标签页和浏览活动