我的 manifest.json
文件中有以下代码:
{
"name": "Test",
"description": "test of Context Menus",
"version": "0.0.1",
"permissions": [
"contextMenus"
],
"background": {
"persistent": false,
"scripts": ["background.js"]
},
"manifest_version": 2
}
这是我的 background.js
文件:
chrome.runtime.onInstalled.addListener(function() {
var parent = chrome.contextMenus.create({"title": "TEST", "contexts":["all"], "id": "parent"});
var child1 = chrome.contextMenus.create({"title": "Test2", "parentId": "parent", "id": "child1", "onclick": showURL, "contexts": ["all"]});
});
这是我的 showURL
函数(在 background.js
文件中)注意:这位于文档的最顶部:
function showURL() {
alert(document.URL);
}
但是运行此命令会使 child1
项消失。这是为什么?
注意:当我删除 "onclick": showURL,
时,它会显示 child1
项。
所以,我知道 onclick
有问题,但我不知道是什么!
请帮帮我,我不知道代码有什么问题!根据 Google 的 API 文档,我认为语法是正确的,那么哪里出了问题??
这应该是一个学习项目 - 学习 Chrome 扩展 API 的简单部分 - 但我已经遇到了问题!我知道编程是一项“有问题”的工作,但是,来吧!一定有人知道解决办法!
最佳答案
当您阅读the docs时,你还没有足够仔细地阅读它们:
(optional) onclick:
A function that will be called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for chrome.contextMenus.onClicked.
list 中的"persistent": false
定义了一个事件页面。你应该restructure your code to fit ,并对 contextMenus
使用基于事件的点击处理。
P.S.:请注意,事件页面在概念上比持久后台页面更难编程。如果这是一次学习经历,您可以尝试切换离开事件页面。
关于javascript - 将 `onclick` 与上下文菜单子(monad)项一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25001919/