How to assign Keyboard Shortcut to run a function in Chrome Extension Manifest v3

762 views
Skip to first unread message

Jack

unread,
Jul 8, 2021, 6:21:44 PM7/8/21
to Chromium Extensions

I'm stuck trying to implement the Action command so that a keyboard shortcut will trigger the function inside background.js. The current code results in nothing happening when the keyboard shortcut is pressed.

Ideally the keyboard shortcut would trigger the function reddenPage inside background.js.

I assume some code needs to be placed in background.js, I'm just not sure where or what the code should be. Any help is much appreciated!

Manifest.json

{

  "name": "Page Redder",

  "action": {},

  "manifest_version": 3,

  "version": "0.1",

  "description": "Turns the page red when you click the icon",

  "permissions": [

    "activeTab",

    "scripting"

  ],

  "background": {

    "service_worker": "background.js"

  },

  "commands": {

    "_execute_action": {

      "suggested_key": {

        "default": "Ctrl+Shift+F",

        "mac": "MacCtrl+Shift+F"

      }

    }

  }

}

background.js






function reddenPage() {

document.body.style.backgroundColor = 'red';

}




chrome.action.onClicked.addListener((tab) => {

chrome.scripting.executeScript({

target: { tabId: tab.id },

function: reddenPage

});

});


Simeon Vincent

unread,
Jul 8, 2021, 6:31:15 PM7/8/21
to Jack, Chromium Extensions
At a glance your code looks good. Does the extension work as expected when you click the extension's action? If so, you might want to check chrome://extensions/shortcuts to verify that this keyboard shortcut is being assigned as expected.

We also have an example of a command invoking an action in the Commands API docs.  

Simeon - @dotproto
Chrome Extensions DevRel


--
You received this message because you are subscribed to the Google Groups "Chromium Extensions" group.
To unsubscribe from this group and stop receiving emails from it, send an email to chromium-extens...@chromium.org.
To view this discussion on the web visit https://groups.google.com/a/chromium.org/d/msgid/chromium-extensions/3c64dc27-21bd-4a7b-9901-bc0ce31480f4n%40chromium.org.

Jack

unread,
Jul 9, 2021, 3:25:09 PM7/9/21
to Chromium Extensions, Simeon Vincent, Chromium Extensions, Jack
I checked chrome://extensions/shortcuts and saw that the shortcut is appropriately assigned. It's working now - so weird. 

Thanks Simeon!

Reply all
Reply to author
Forward
0 new messages