-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
Copy pathbackgroundtab.ts
44 lines (36 loc) · 1.45 KB
/
backgroundtab.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { SPAN_STATUS_ERROR, getActiveSpan, getRootSpan } from '@sentry/core';
import { spanToJSON } from '@sentry/core';
import { logger } from '@sentry/utils';
import { DEBUG_BUILD } from '../debug-build';
import { WINDOW } from '../helpers';
/**
* Add a listener that cancels and finishes a transaction when the global
* document is hidden.
*/
export function registerBackgroundTabDetection(): void {
if (WINDOW && WINDOW.document) {
WINDOW.document.addEventListener('visibilitychange', () => {
const activeSpan = getActiveSpan();
if (!activeSpan) {
return;
}
const rootSpan = getRootSpan(activeSpan);
if (WINDOW.document.hidden && rootSpan) {
const cancelledStatus = 'cancelled';
const { op, status } = spanToJSON(rootSpan);
if (DEBUG_BUILD) {
logger.log(`[Tracing] Transaction: ${cancelledStatus} -> since tab moved to the background, op: ${op}`);
}
// We should not set status if it is already set, this prevent important statuses like
// error or data loss from being overwritten on transaction.
if (!status) {
rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message: cancelledStatus });
}
rootSpan.setAttribute('sentry.cancellation_reason', 'document.hidden');
rootSpan.end();
}
});
} else {
DEBUG_BUILD && logger.warn('[Tracing] Could not set up background tab detection due to lack of global document');
}
}