Search code examples
javascriptgoogle-chromegoogle-chrome-extensionshortcut

Custom chrome extension shortcuts not working


I am creating my own chrome extension. I would like to be able to run a script after clicking a shortcut. My manifest looks like this:

{
    "name": "Test",
    "version": "0.0.1",
    "manifest_version": 2,
    "description": "Test ext",
    "homepage_url": "",
    "icons": {
      "16": "icons/test-icon.jpg",
      "48": "icons/test-icon.jpg",
      "128": "icons/test-icon.jpg"
    },
    "default_locale": "en",
    "background": {
      "scripts": ["src/bg/background.js"],
      "persistent": true
    },
    "commands":{
      "run-script": {
        "suggested_key": {
          "default": "Ctrl+E",
          "windows": "Ctrl+E",
          "mac": "Command+E"
        },
        "description": "Run",
        "global": true
      }
    },
    "browser_action": {
      "default_icon": "icons/test-icon.jpg",
      "default_title": "browser action demo",
      "default_popup": "src/browser_action/browser_action.html"
    },
    "permissions": ["tabs", "https://*/*", "storage"],
    "content_scripts": [
      {
        "matches": [
          "https://www.test.co.uk/*"
        ],
        "js": ["src/inject/inject.js"]
      }
    ]
  }

So I have extension with simple UI and start button. I would like to be able to use CTRL+E or CMD+E to run a script after that. When I go to extensions in chrome settings I see shortcut:

enter image description here

So as I understand I should get console.log and I am getting it in the background console. But what if I would like to use that shortcut for changing actual page to another? How can I achieve that? This is not working:

chrome.commands.onCommand.addListener((command) => {
  location.replace(
    `https://www.solebox.com/en_GB/checkout?stage=shipping#shipping`
  );
});

Nothing is happening.


Solution

  • Fixed by just making:

    chrome.commands.onCommand.addListener((command) => {
      chrome.tabs.update({
        url: `https://www.google.com`,
      });
    });
    

    As I understand I cannot use location.replace or any other js methods in background.js. I have to use only chrome commands to switch page and then use my inject.js file to make some changes on a page.