Brian Spilner
Brian Spilner

Reputation: 673

Chrome commands API

I've loaded this sample extension from Chrome docs which uses the commands API.

manifest.json

{
"name": "Sample Extension Commands extension",
  "description": "Press Ctrl+Shift+F (Command+Shift+F on a Mac) to open the browser action popup, press Ctrl+Shift+Y to send an event (Command+Shift+Y on a Mac).",
  "version": "1.0",
  "manifest_version": 2,
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "browser_action": {
    "default_popup": "browser_action.html"
  },
  "commands": {
    "toggle-feature": {
      "suggested_key": { "default": "Ctrl+Shift+Y" },
      "description": "Send a 'toggle-feature' event to the extension"
    },
    "_execute_browser_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+F",
        "mac": "MacCtrl+Shift+F"
      }
    }
  }
}

background.js

chrome.commands.onCommand.addListener(function(command) {
  console.log('onCommand event received for message: ', command);
});

Very simple, yet the listener callback is not getting triggered - I get no output in the console, nor any errors. If I use other API, for example tabs, my listeners are getting triggered as they should, it's just the commands API that doesn't work for me.

Upvotes: 14

Views: 5114

Answers (2)

yrizk
yrizk

Reputation: 394

I was running into the same issue and these suggestions didn't help. Here's what I figured out: since you declared the script with the listener in the background: {} section, it logs to a background page. You can see that log specifically by clicking "Inspect background page" right below the extension at the chrome://extensions. that's where the listener logs to.

Upvotes: 0

Michael Johansen
Michael Johansen

Reputation: 5096

Commenter rsanchez provides the correct answer:

Are you working with an unpacked extension? You need to remove and re-add the extension for suggested shorcut keys to be considered.

Upvotes: 16

Related Questions