Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension error with 'onCommand'

I'm getting the error "Uncaught TypeError: Cannot read property 'onCommand' of undefined" while running a Chrome Extension with the following content:

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.");
  }
}); 

All it's supposed to do is print "Ctrl-M successful" if Ctrl-M is pressed and print "Ctrl-L successful" if Ctrl-L is pressed.

This question appears to contain an answer to this problem, but I don't understand the answer and can't add a comment to ask for further explanation since I don't have enough reputation: "Is your onCommand listener defined in a content script? It probably won't work there; you need to include it in a background page or an action popup." How am I supposed to define onCommand in the background page?? I couldn't find anything on that anywhere, whether in the API or via Googling in general.

I also tried reloading the extension and manually inputting the keyboard shortcuts manually as suggested here, to no avail.

What am I missing here?

like image 365
user124384 Avatar asked Jan 11 '23 09:01

user124384


1 Answers

The chrome.commands is not available by content_scripts (as defined in https://developer.chrome.com/extensions/content_scripts).

To get it working you can change your manifest to :

{
  "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"
    }
  }
}

In addition Ctlr+L is not working (at least on Mac) as already used by chrome to get focus on adress bar.

The element will be visible in the console of the extension. To see it open chrome://extensions/ and click on the Inspect views: background page of your extension.

like image 116
Vincent M. Avatar answered Jan 18 '23 23:01

Vincent M.