我正在使用以下方法从非持久性后台脚本添加上下文菜单项:
chrome.contextMenus.create({
title: 'Get Code',
id: 'myUniqueIdForThisExtension123',
contexts: ['all'],
onclick: onClickHandler
});
function onClickHandler() {}
documentation简单地说:
The unique ID to assign to this item. Mandatory for event pages. Cannot be the same as another ID for this extension.
所以我添加了一个唯一的ID,但我仍然不能让它工作。上下文菜单中没有插入任何新内容。
最佳答案
你是说你有一个非持久性背景页面,所以你应该有一个看起来像这样的 manifest.json
文件:
{
"manifest_version": 2,
"name": "My extension",
"description": "My description",
"version": "1",
"permissions": ["contextMenus"],
"background": {
"persistent": false,
"scripts": [
"/background.js"
]
}
}
现在,由于您有一个非持久性后台页面,因此当您需要使用上下文菜单时,您必须使用正确的监听器来“唤醒它”。
引自official documentation (注意:此链接指向 2014 年文档的存档副本并且已过时):
Best practices when using event pages:
[...]
- If you're using the context menus API, pass a string id parameter to
contextMenus.create
, and use thecontextMenus.onClicked
callback instead of anonclick
parameter tocontextMenus.create
.
所以,很简单,您的错误是在 background.js
中使用 onclick
参数而不是 contextMenus.onClicked.addListener()
方法>.
解决方案
我已经说过你应该使用onClicked
事件,但我想补充一点,引用x a's answer :
You should register a context menu via
contextMenus.create
in the event handler ofruntime.onInstalled
, as these context menu registrations persist anyway.
很简单,一旦创建了上下文菜单,它就会保留在您的扩展中,最好只定义一次:当您的扩展被安装(或更新)时,并在每次加载后台页面时添加监听器.
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
title: 'My menu',
id: 'menu1', // you'll use this in the handler function to identify this context menu item
contexts: ['all'],
});
});
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId === "menu1") { // here's where you'll need the ID
// do something
}
});
这就是您在事件页面中创建上下文菜单所需要的,如 documentation page 中所示 chrome.contextMenus
API。
关于javascript - 在非持久性后台脚本上添加上下文菜单项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26245888/