运行包含以下内容的Chrome扩展程序时,我收到错误“Uncaught 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成功”。
This question似乎包含对此问题的回答,但我不明白答案,因为我没有足够的声誉而无法添加评论以要求进一步解释:“是您的{在内容脚本中定义的监听器?它可能无法在那里工作;您需要将它包含在后台页面或动作弹出窗口中。“我该如何在后台页面中定义onCommand
?无论是在API还是通过谷歌搜索,我都找不到任何东西。
我也尝试重新加载扩展程序,并按照建议here手动手动输入键盘快捷键,但无济于事。
我在这里缺少什么?
答案 0 :(得分:4)
content_scripts不提供chrome.commands(在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 /,然后点击扩展程序的Inspect views:background页面。