Skip to content

Commit d155bfb

Browse files
authored
[CI 3890] switch beforeunload with visibilitychange (#346)
* change to pagehide * change to visibilitychange * update comment * Address comments * Add check when changed to visible * lint * Add visibilityState to tests * lint * combine if statements
1 parent a50123d commit d155bfb

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

spec/mocha.helpers.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
/* eslint-disable import/no-unresolved, import/extensions */
22
const qs = require('qs');
3+
const sinon = require('sinon');
34
const store = require('../test/utils/store');
45

56
// Trigger browser resize event
@@ -21,7 +22,8 @@ const triggerResize = () => {
2122
const triggerUnload = () => {
2223
const unloadEvent = document.createEvent('Event');
2324

24-
unloadEvent.initEvent('beforeunload', true, true);
25+
unloadEvent.initEvent('visibilitychange', true, true);
26+
sinon.stub(document, 'visibilityState').value('hidden');
2527

2628
global.window.unload = () => {
2729
global.window.dispatchEvent(unloadEvent);

src/utils/request-queue.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,18 @@ class RequestQueue {
1919
? true
2020
: false; // Defaults to 'false'
2121

22-
// Mark if page environment is unloading
23-
helpers.addEventListener('beforeunload', () => {
24-
this.pageUnloading = true;
22+
helpers.addEventListener('visibilitychange', () => {
23+
// Mark if page environment is unloading
24+
if (document.visibilityState === 'hidden') {
25+
this.pageUnloading = true;
26+
} else if (document.visibilityState === 'visible' && this.pageUnloading === true) {
27+
// Send events once page is visible again
28+
this.pageUnloading = false;
29+
30+
if (this.sendTrackingEvents) {
31+
this.send();
32+
}
33+
}
2534
});
2635

2736
if (this.sendTrackingEvents) {
@@ -183,7 +192,7 @@ class RequestQueue {
183192
if (this.options && this.options.trackingSendDelay === 0) {
184193
this.sendEvents();
185194
} else {
186-
// Defer sending of events to give beforeunload time to register (avoids race condition)
195+
// Defer sending of events to give visibilitychange time to register (avoids race condition)
187196
setTimeout(this.sendEvents.bind(this), (this.options && this.options.trackingSendDelay) || 250);
188197
}
189198
}

0 commit comments

Comments
 (0)