Debugging browser extension based on manifest version 3

Posted on Jan 19, 2023
tl;dr: A simple pro-tip how to debug browser extension code easier

Developers are facing with debugging code on a daily basis. When developing browser extension that is using service worker inside it could be a little hard sometimes to debug it properly. In this article I will explain how make it in easier way.

Catching actions that are done after starting a service worker

I wanted to discover a specific case when our extension is doing some task or requests right after calling a service worker. In order to catch actions done there we could use a simple trick.

In the script marked as dedicated to service worker (that applies to both JS and TS versions):

{
  "background": {
    "service_worker": "src/serviceWorker.ts"
  }
}

Instead of calling methods we want directly:

// src/serviceWorker.ts

const x = 10;
const y = 20;
const sum = x + y;
console.log("Result: " + sum);

We could do:

// src/serviceWorker.ts

// Delay in miliseconds
const delay = 15000;

setTimeout(() => {
    const x = 10;
    const y = 20;
    const sum = x + y;
    console.log("Result: " + sum);
}, delay);

That approach will give us time on opening background page after injecting local version of our extension in the browser. Thanks to that we will be able to: check all logs, network requests, breakpoints from the start.

Hope you would find this post useful!