Adding Sentry Error Tracking to a Chrome Extension

How to add Sentry to a chrome extension. Plain and simple.

I couldn’t find any good resources for adding sentry to a chrome extension. Once I finally figured it out, I thought it would be helpful to write a short post explaining how to do it.

 

1. Create a file in your chrome extension’s root directory called sentry.js

2. Copy the contents from https://browser.sentry-cdn.com/6.3.5/bundle.es6.js or the bundle of your preference into sentry.js

3. Add sentry.js to your manifest:

 

For a background script:
  "background": {
    "scripts": ["background.js", "sentry.js"],
  },

 

For a content script:
  "content_scripts": [
    {
      "js": ["content.js", "sentry.js"],
    }
  ],

 

4. Initialize Sentry:

Adding Sentry to a background script or a content script looks the same:

window.addEventListener("load", function () {
  Sentry.init({
    dsn:
      "YOUR_DSN_HERE",
    tracesSampleRate: 1.0,
  });
});

Note: The window.addEventListener piece is critical here. The page needs to load the script for you to have access to the Sentry variable.

Important!

To find your DSN, go to Sentry and go to Settings –> Projects –> YOUR PROJECT –> Client Keys (under SDK setup)

 

5. That’s it! Sentry should now be initialized and catch any errors in your chrome extension.

 

Gotchas:

 

Async messages don’t bubble up to the main onerror listener, so if you have any code that looks like this:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

})

 

You’ll want to add:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  Sentry.wrap(function () {

  })
})

 

I figured this out with the help of this github comment:

https://github.com/getsentry/sentry-javascript/issues/2170#issuecomment-518168871

Still need help?

Didn't find what you need? I'm happy to help folks out.

Feel free to email me at