Custom chrome extension shortcuts not working

Viewed 233

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.

3 Answers

// background.js

chrome.commands.onCommand.addListener((command) => {
  // location.replace(...)
  chrome.tabs.query({active: true}, function(tabs) {
    chrome.tabs.update(tabs[0].id, {url: 'https://...'});
  });
});

Ctrl+E is an shortcut registerd by chrome itself, maybe try Ctrl+Q.

It is also important that you open the console of the service worker/background script, the log would show up here.

Chrome extension view

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.

Related