共享环境 / 浏览器扩展
了解如何在共享环境中使用 Sentry(例如在浏览器扩展或 VSCode 扩展中)。
我们建议在共享环境中使用 JavaScript SDK 8.x
及以上版本。请参阅我们的 迁移文档,以从旧版本 SDK 升级到 8.x
及以上版本。
这些最佳实践适用于以下使用场景:
- 浏览器扩展
- VSCode 扩展
- 第三方小部件
- 插件架构
- 库
- 任何可能在同一环境中运行多个 Sentry 实例的其他场景
在设置 Sentry 的共享环境中,如果可能有多个 Sentry 实例运行,不应使用 Sentry.init()
,因为这会污染全局状态。如果您的浏览器扩展使用 Sentry.init()
,并且网站也使用 Sentry,则扩展可能会将事件发送到网站的 Sentry 项目,反之亦然。
对于上述使用场景,请按照以下示例手动设置客户端。此外,避免添加使用全局状态的集成,如 Breadcrumbs
或 GlobalHandlers
。进一步地,一些使用全局状态的默认集成需要像下面的示例那样进行过滤。在这种情况下,最佳实践是避免使用任何集成,并依赖手动捕获错误。
import {
BrowserClient,
defaultStackParser,
getDefaultIntegrations,
makeFetchTransport,
Scope,
} from "@sentry/browser";
// filter integrations that use the global variable
const integrations = getDefaultIntegrations({}).filter(
(defaultIntegration) => {
return !["BrowserApiErrors", "Breadcrumbs", "GlobalHandlers"].includes(
defaultIntegration.name,
);
},
);
const client = new BrowserClient({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
transport: makeFetchTransport,
stackParser: defaultStackParser,
integrations: integrations,
});
const scope = new Scope();
scope.setClient(client);
client.init(); // initializing has to be done after setting the client on the scope
// You can capture exceptions manually for this client like this:
scope.captureException(new Error("example"));
为了使其更简单但仍保持 “让 Sentry 处理未处理的错误”,您可以使用以下代码:
// Init Sentry as shown above
try {
// Your goes code here
// as in import and execute your code here
// and if an error occurs, Sentry will capture it
} catch (error) {
scope.captureException(error);
}
如果您发现 Sentry 没有捕获来自浏览器扩展的错误事件,可能是启用了入站过滤器。您可以通过进入 项目设置 > 入站过滤器 并禁用过滤掉由浏览器扩展引起的已知错误来解决此问题。
了解更多关于入站过滤器的信息,请参阅产品文档中的 入站过滤器。
自版本 8.37.0
起在所有基于浏览器的 SDK 中可用
如果由于某种原因,SDK 错误地检测到它是在浏览器扩展中初始化的,您可以通过指定跳过此检查:
import * as Sentry from "@sentry/browser";
Sentry.init({
dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
skipBrowserExtensionCheck: true,
// ...
});
如果您确实在浏览器扩展或其他共享环境中使用 SDK,则不应使用此选项。 通过 Sentry.init
初始化 SDK 并不会比本页面描述的手动设置客户端和作用域有更多的优势。 这样做可能会导致配额增加、无法处理的问题、与其他 Sentry SDK 的干扰以及数据泄漏。
此选项纯粹是为了应对我们的浏览器扩展检查错误检测到浏览器扩展的情况。 例如,这可能是一个暴露类似浏览器扩展的全局 API 的跨平台应用程序框架。