WittCode💻

Speed Up your Chrome Extension Development with THIS TRICK!

By

Learn how to speed up your chrome extension development by using service workers, the Commands API, and the Runtime API.

Table of Contents 📖

Extension Reloads

When building a chrome extension, we often have to reload the extension using the Extensions Management page.

Image

Constantly reloading the extension manually can slow down development and just lead to a poor developer experience. We can speed up this process drastically using the Commands API.

Commands API

The chrome Commands API is used to add keyboard shortcuts that trigger actions. For example, we can create a keyboard shortcut to reload the extension. This is what we will do now. To use the Commands API we need to add it as a permission to our manifest file. We also create the command in the manifest file.

{
  "manifest_version": 3,
  "name": "My Chrome Extension",
  "version": "1.0.0",
  "description": "My AMAZING Chrome Extension!",
  "permissions": [
    "commands"
  ],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content/example.js"],
      "css": ["content/example.css"]
    }
  ],
  "background": {
    "service_worker": "background/service.js",
    "type": "module"
  },
  "commands": {
    "reload": {
      "suggested_key": {
        "default": "Ctrl+Shift+E",
        "mac": "Command+Shift+E"
      },
      "description": "Reload the extension."
    }
  }
}

Here we give the command the name reload but it can be any name. Next we use the suggested_key key to set the default keyboard shortcuts for the command with a specific command for MacOS.

ERROR: Not all keys are usable for command shortcuts. Key definitions are also case sensitive.

Handling the Command

Now that we have a keyboard shortcut setup, lets attach a listener to our service worker to listen for it.

WARNING: As this command is specific for development, it might be best to wrap this in an if block that checks for the current environment. Or just remove it before publishing the project.

chrome.commands.onCommand.addListener((shortcut) => {
  if (shortcut === 'reload') {
    console.log('Reloading extension!');
    chrome.runtime.reload();
  }
});

Here we listen out for any commands. When we receive one we check if it is the reload shortcut. If it is we use the Runtime API to reload the extension. Now focus on the browser that the extension is installed on, press the command keys to reload the extension, and then look for the changes.

Why the Service Worker?

The service worker is the best place to put this listener as the Commands API is not available in content scripts. It is available in the popup but the popup needs to be open to receive the command.