Skip to main content

[JavaScript] Do I need to avoid Sentry.init in a browser extension?

Issue

My browser extension uses Sentry.init() or the global Sentry client (sometimes called the global scope). I need to know whether I must isolate Sentry from the host page.

Applies To

  • All SaaS Customers and Self-Hosted Users

  • JavaScript SDK (Browser), version 8.x and above

  • Browser Extensions / Shared Environments

Resolution

Do not call Sentry.init() in a browser extension. Sentry.init() writes global state. If the host page also uses Sentry, events can go to the wrong project.

Create a BrowserClient and a Scope yourself. Leave out integrations that patch global browser APIs. Capture errors on that scope.

import {
  BrowserClient,
  defaultStackParser,
  getDefaultIntegrations,
  makeFetchTransport,
  Scope,
} from "@sentry/browser";const integrations = getDefaultIntegrations({}).filter(
  (defaultIntegration) => {
    return ![
      "BrowserApiErrors",
      "BrowserSession",
      "Breadcrumbs",
      "ConversationId",
      "GlobalHandlers",
      "FunctionToString",
    ].includes(defaultIntegration.name);
  },
);const client = new BrowserClient({
  dsn: "https://<key>@o<orgId>.ingest.sentry.io/<projectId>",
  transport: makeFetchTransport,
  stackParser: defaultStackParser,
  integrations: integrations,
});const scope = new Scope();
scope.setClient(client);
client.init();scope.captureException(new Error("example"));

Do not set skipBrowserExtensionCheck: true so you can keep using Sentry.init() in a real extension. That option is only for apps that are not extensions but look like one to the SDK.

If events from the extension do not appear, check that the browser-extension inbound filter is off under Settings > Projects > [your project] > Inbound Filters.

For Chrome background scripts, content scripts, and popups, see How do I integrate Sentry with a Chrome extension?. For the full shared-environment guide, see Shared Environments / Browser Extensions.

Did this answer your question?