Kee*_*ker 8 google-chrome google-chrome-extension
我正在写我的第一个Chrome扩展程序.我已经使用了许可,但我到处都看到了我的按钮.
我怎样才能在我正在编写扩展名的地址上显示按钮?
Rob*_*b W 13
尽管@Sorter的答案有效,但它并不是解决问题的最佳方法.
首先,它并不总是有效.如果使用的页面history.pushState
,页面操作将消失,直到您再次触发onUpdated
或onHighlighted
事件Chromium问题231075后才会返回.
其次,该方法效率低,因为它是在所有页面上每次更新选项卡状态时触发的.
使页面操作出现在某些域上的最有效和最可靠的方法是使用declarativeContent
API.这仅在Chrome 33之后可用.在此之前,webNavigation
API是最合适的API.与使用API的方法相比,这些API的优点tabs
是可以安全地使用事件页面,因为您可以声明URL过滤器.使用这些URL过滤器,只有在导航到与URL过滤器匹配的页面时才会触发事件.因此,在真正需要之前,您的扩展/事件页面不会被激活(=没有浪费的RAM或CPU).
这是background.js
使用webNavigation
API 的最小示例():
function onWebNav(details) {
if (details.frameId === 0) {
// Top-level frame
chrome.pageAction.show(details.tabId);
}
}
var filter = {
url: [{
hostEquals: 'example.com'
}]
};
chrome.webNavigation.onCommitted.addListener(onWebNav, filter);
chrome.webNavigation.onHistoryStateUpdated.addListener(onWebNav, filter);
Run Code Online (Sandbox Code Playgroud)
manifest.json
:
{
"name": "Name ",
"version": "1",
"manifest_version": 2,
"background": {
"scripts": ["background.js"],
"persistent": false
},
"page_action": {
"default_title": "Only visible on stackoverflow.com"
},
"permissions": [
"webNavigation"
]
}
Run Code Online (Sandbox Code Playgroud)
如果您定位Chrome 33及更高版本,则您也可以使用declarativeContent API.只需将"webNavigation"权限替换为"declarativeContent",并使用以下后台脚本(background.js):
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: {
hostEquals: 'example.com'
}
})
],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
Run Code Online (Sandbox Code Playgroud)
在这两个示例中,我使用了与域匹配的UrlFilterexample.com
.
创建 background.js 来检查更新和突出显示的选项卡。
function checkForValidUrl(tabId, changeInfo, tab) {
// If 'example.com' is the hostname for the tabs url.
var a = document.createElement ('a');
a.href = tab.url;
if (a.hostname == "example.com") {
// ... show the page action.
chrome.pageAction.show(tabId);
}
};
// Listen for any changes to the URL of any tab.
chrome.tabs.onUpdated.addListener(checkForValidUrl);
//For highlighted tab as well
chrome.tabs.onHighlighted.addListener(checkForValidUrl);
Run Code Online (Sandbox Code Playgroud)
以类似的方式创建 popup.html 和 popup.js。
您可以在内容脚本 (popup.js) 中使用 background.js 中定义的变量
chrome.extension.getBackgroundPage().variableName
这是示例扩展下载链接。
为了您的参考和方便,这里是示例 manifest.json 文件
{
"manifest_version": 2,
"name": "Example Extension",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"page_action":{
"default_icon": "images/icon_16.png",
"default_popup": "popup.html",
"default_title": "Title for the extension"
},
"permissions": [
"tabs"
]
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6956 次 |
最近记录: |