diff --git a/spec/mocha.helpers.js b/spec/mocha.helpers.js index e3ee9060..fb7ac900 100644 --- a/spec/mocha.helpers.js +++ b/spec/mocha.helpers.js @@ -1,5 +1,6 @@ /* eslint-disable import/no-unresolved, import/extensions */ const qs = require('qs'); +const sinon = require('sinon'); const store = require('../test/utils/store'); // Trigger browser resize event @@ -21,7 +22,8 @@ const triggerResize = () => { const triggerUnload = () => { const unloadEvent = document.createEvent('Event'); - unloadEvent.initEvent('beforeunload', true, true); + unloadEvent.initEvent('visibilitychange', true, true); + sinon.stub(document, 'visibilityState').value('hidden'); global.window.unload = () => { global.window.dispatchEvent(unloadEvent); diff --git a/src/utils/request-queue.js b/src/utils/request-queue.js index 02146c9a..50d9882c 100644 --- a/src/utils/request-queue.js +++ b/src/utils/request-queue.js @@ -19,9 +19,18 @@ class RequestQueue { ? true : false; // Defaults to 'false' - // Mark if page environment is unloading - helpers.addEventListener('beforeunload', () => { - this.pageUnloading = true; + helpers.addEventListener('visibilitychange', () => { + // Mark if page environment is unloading + if (document.visibilityState === 'hidden') { + this.pageUnloading = true; + } else if (document.visibilityState === 'visible' && this.pageUnloading === true) { + // Send events once page is visible again + this.pageUnloading = false; + + if (this.sendTrackingEvents) { + this.send(); + } + } }); if (this.sendTrackingEvents) { @@ -182,7 +191,7 @@ class RequestQueue { if (this.options && this.options.trackingSendDelay === 0) { this.sendEvents(); } else { - // Defer sending of events to give beforeunload time to register (avoids race condition) + // Defer sending of events to give visibilitychange time to register (avoids race condition) setTimeout(this.sendEvents.bind(this), (this.options && this.options.trackingSendDelay) || 250); } }