有没有一种方法可以为一个网站定义pageAction?我看到了示例,它们都使用background.js在该文件中显示chrome.pageAction.show(tabId)

最佳答案

为了显示特定网站的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>
  它可以访问:
  访问您的标签和浏览活动

关于javascript - chrome扩展标签没有背景页面的操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13895291/

10-09 02:14
查看更多