运行具有以下内容的Chrome扩展程序时出现错误“未捕获的TypeError:无法读取未定义的属性'onCommand'”:
manifest.json:
{
"name": "Test",
"description": "Key command test.",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [ {
"js": ["background_test.js"],
"matches": [ "http://*/*", "https://*/*"]
}],
"commands": {
"Ctrl+M": {
"suggested_key": {
"default": "Ctrl+M",
"mac": "Command+M"
},
"description": "Ctrl+M."
},
"Ctrl-L": {
"suggested_key": {
"default": "Ctrl+L",
"mac": "Command+L"
},
"description": "Ctrl+L"
}
}
}
background_test.js:
chrome.commands.onCommand.addListener(function(command) {
if (command === "Ctrl+L") {
console.log("Ctrl-L successful.");
}
else if (command === "Ctrl+M") {
console.log("Ctrl+M successful.");
}
});
它要做的就是如果按Ctrl-M,则打印“ Ctrl-M成功”,如果按Ctrl-L,则打印“ Ctrl-L成功”。
该问题似乎包含该问题的答案,但由于我没有足够的声誉,因此我不明白答案,也无法添加评论以要求进一步的解释:“您的onCommand
监听器是否在内容脚本中定义?它可能在那里不起作用;您需要将其包含在后台页面或操作弹出窗口中。” 我应该如何onCommand
在后台页面中定义?无论在API还是通过Googling,我在任何地方都找不到任何东西。
我也尝试重新加载扩展,并按照此处的建议手动输入键盘快捷键,但无济于事。
我在这里想念什么?
chrome.commands不能由content_scripts使用(在https://developer.chrome.com/extensions/content_scripts中定义)。
要使其正常工作,您可以将清单更改为:
{
"name": "Test",
"description": "Key command test.",
"version": "1.0",
"manifest_version": 2,
"permissions": [
"<all_urls>"
],
"background":
{
"scripts": ["background_test.js"],
"persistent": true
},
"commands": {
"Ctrl+M": {
"suggested_key": {
"default": "Ctrl+M",
"mac": "Command+M"
},
"description": "Ctrl+M."
},
"Ctrl+L": {
"suggested_key": {
"default": "Ctrl+L",
"mac": "Command+L"
},
"description": "Ctrl+L"
}
}
}
此外,Ctlr + L不能正常运行(至少在Mac上如此),因为chrome已经使用它来获取地址栏上的焦点。
该元素将在扩展的控制台中可见。要查看它,请打开chrome:// extensions /,然后点击扩展程序的检查视图:背景页面。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句