【问题标题】:Chrome extension error with 'onCommand'“onCommand”的 Chrome 扩展程序错误
【发布时间】:2014-08-05 07:01:17
【问题描述】:

在运行具有以下内容的 Chrome 扩展程序时,我收到错误“未捕获的类型错误:无法读取未定义的属性 '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在内容脚本中定义的侦听器?它可能不会在那里工作;您需要将它包含在背景页面或操作弹出窗口中。我应该如何在后台页面中定义onCommand?我在任何地方都找不到任何东西,无论是在 API 中还是通过谷歌搜索。

我还尝试按照here 的建议手动重新加载扩展程序并手动输入键盘快捷键,但无济于事。

我在这里错过了什么?

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension keyboard-shortcuts


    【解决方案1】:

    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: 您的扩展程序的背景页面。

    【讨论】:

    • 哦,伙计,我永远也想不通(嗯,很明显)。这行得通。谢谢!!
    猜你喜欢
    • 2016-08-20
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多