Chrome扩展错误'onCommand'

Chrome extension error with 'onCommand'

本文关键字:onCommand 扩展 错误 Chrome      更新时间:2023-09-26

我得到的错误"Uncaught TypeError:无法读取属性'onCommand'的未定义",而运行Chrome扩展与以下内容:

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中还是通过谷歌搜索。

我也尝试重新加载扩展和手动输入键盘快捷键手动建议这里,无济于事。

我在这里错过了什么?

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/并点击你的扩展的Inspect views: background页面。