Skip to content

Commit e69e112

Browse files
committed
fix onHidden change
1 parent 82ebb43 commit e69e112

File tree

2 files changed

+27
-9
lines changed

2 files changed

+27
-9
lines changed

packages/browser-utils/src/metrics/web-vitals/lib/onHidden.ts

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,31 @@
1616

1717
import { WINDOW } from '../../../types';
1818

19-
// sentry: This function is used in web-vitals 4.2.4 but we continue
20-
// to use it in our v5 version. We still need it for the FID logic
21-
// and one internal use case (TBD if we switch over) in both.
22-
export const onHidden = (cb: () => void) => {
23-
WINDOW.document?.addEventListener('visibilitychange', () => {
24-
if (WINDOW.document?.visibilityState === 'hidden') {
25-
cb();
19+
export interface OnHiddenCallback {
20+
(event: Event): void;
21+
}
22+
23+
// Sentry-specific change:
24+
// This function's logic was NOT updated to web-vitals 4.2.4 or 5.x but we continue
25+
// to use the web-vitals 3.5.2 versiondue to us having stricter browser support.
26+
// PR with context that made the changes: https://github.com/GoogleChrome/web-vitals/pull/442/files#r1530492402
27+
// The PR removed listening to the `pagehide` event, in favour of only listening to `visibilitychange` event.
28+
// This is "more correct" but some browsers we still support (Safari <14.4) don't fully support `visibilitychange`
29+
// or have known bugs w.r.t the `visibilitychange` event.
30+
// TODO (v10): If we decide to drop support for Safari 14.4, we can use the logic from web-vitals 4.2.4
31+
// In this case, we also need to update the integration tests that currently trigger the `pagehide` event to
32+
// simulate the page being hidden.
33+
export const onHidden = (cb: OnHiddenCallback) => {
34+
const onHiddenOrPageHide = (event: Event) => {
35+
if (event.type === 'pagehide' || WINDOW.document?.visibilityState === 'hidden') {
36+
cb(event);
2637
}
27-
});
38+
};
39+
40+
if (WINDOW.document) {
41+
addEventListener('visibilitychange', onHiddenOrPageHide, true);
42+
// Some browsers have buggy implementations of visibilitychange,
43+
// so we use pagehide in addition, just to be safe.
44+
addEventListener('pagehide', onHiddenOrPageHide, true);
45+
}
2846
};

packages/browser-utils/src/metrics/web-vitals/lib/whenIdleOrHidden.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ import { runOnce } from './runOnce.js';
2222
* if the browser's visibility state is (or becomes) hidden.
2323
*/
2424
export const whenIdleOrHidden = (cb: () => void) => {
25-
const rIC = globalThis.requestIdleCallback || setTimeout;
25+
const rIC = WINDOW.requestIdleCallback || WINDOW.setTimeout;
2626

2727
// If the document is hidden, run the callback immediately, otherwise
2828
// race an idle callback with the next `visibilitychange` event.

0 commit comments

Comments
 (0)