Search code examples
javascriptgoogle-chrome-extensiondomdocumentsentrychrome-extension-manifest-v3

How to use Sentry in chrome extension


I am trying to use Sentry in a chrome extension project. Here is a workaround.

If I try this code in background.js file:

import * as Sentry from '@sentry/browser'

Sentry.WINDOW.document = {
  visibilityState: 'hidden',
  addEventListener: () => {},
}

I get an error: TypeError: Cannot set property document of #<Window> which has only a getter

I tried to update code to this:

Object.defineProperty(Sentry.WINDOW, 'document', {
  value: {
    visibilityState: 'hidden',
    addEventListener: () => {},
  },
  configurable: true,
  writable: true,
  enumerable: true,
})

but now I am getting error: TypeError: Cannot redefine property: document.

Any ideas how can I fix this and use Sentry in a browser extension?


Solution

  • I found out the issue. The key is to don't import anything from background.js into content script.

    In my case the whole file background.js was called in my content script, because I imported a variable. For this reason whole background.js was called in content script:

    Sentry.WINDOW.document = {
      visibilityState: 'hidden',
      addEventListener: () => {},
    }
    

    When I moved the variable from background.js to my content script file, I got rid off the error because background.js is called only in service worker now.