我在用chrome.contextMenus.create
函数在我的 Chrome 扩展中创建上下文菜单。但它创造了额外的选择。
我在我的权限内给予了许可manifest.json
文件,添加了这个函数我的background.js
文件并将其添加到我的manifest.json
file.
为什么会发生这种情况?
function getword(info,tab) {
console.log("Word " + info.selectionText + " was clicked.");
chrome.tabs.create({
url: "http://www.google.com/search?q=" + info.selectionText,
});
}
chrome.contextMenus.create({
title: "Search: %s",
contexts:["selection"],
onclick: getword,
});
您的后台代码将执行多次 - 至少在每次浏览器启动/扩展重新加载时,最多每次活动页面 https://developer.chrome.com/extensions/event_pages ("persistent": false
)醒来。
chrome.contextMenus.create https://developer.chrome.com/extensions/contextMenus#method-create按照罐头上的说明进行操作 - 创建一个新条目。每次运行时。这很好,因为通常您想在扩展运行时设置所有内容,但是实际上上下文菜单条目persist扩展重新加载之间- 所以它们不断堆积。
这里有两种方法:
-
Assign an ID to your context entry (which is an arbitrary string); in this case, calling create
again with the same ID will overwrite it raise an error, not create a new one.
chrome.contextMenus.create({
title: "Search: %s",
id: "search",
contexts:["selection"],
onclick: getword,
});
无论如何,这对于稍后操作/引用该条目很有用。
-
呼叫前擦除上下文菜单条目create
:
chrome.contextMenus.removeAll(function() {
chrome.contextMenus.create({
// ...
});
});
这可能看起来多余,但这是确保扩展程序早期版本中的“旧”上下文菜单条目不会保留的最简单方法。
当然,您可以将两者结合起来。
进一步说明:
如果你实际使用的是"persistent": false
活动页面,注意使用onclick
属性是不允许的,因为它会因扩展卸载而失效。更稳健的方法是使用chrome.contextMenus.onClicked
event - 菜单项的 ID 将传递给它以区分选项。
-
由于您很少需要更新上下文菜单项,因此最好将它们隐藏在相应的事件中,chrome.runtime.onStartup https://developer.chrome.com/extensions/runtime#event-onStartup and/or chrome.runtime.onInstalled https://developer.chrome.com/extensions/runtime#event-onInstalled.
但是,请注意,在极少数情况下,您可能会遇到错误:
- 该扩展已安装但被禁用。
- 禁用时会发生更新。
- 此更新实际上应该更改这些事件中任一事件的上下文菜单。
- 然后,再次启用扩展。
在那种情况下,neither事件将会触发。这是一个bug https://bugs.chromium.org/p/chromium/issues/detail?id=388231.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)