diff --git a/src/sendLogs.js b/src/sendLogs.js index 5985644d..860d0ca0 100644 --- a/src/sendLogs.js +++ b/src/sendLogs.js @@ -61,13 +61,25 @@ export function sendOnInterval(logs, config) { */ export function sendOnClose(logs, config) { window.addEventListener("pagehide", function () { - if (config.on && logs.length > 0) { - // NOTE: sendBeacon does not support auth headers, - // so this will fail if auth is required. - // The alternative is to use fetch() with keepalive: true - // https://developer.mozilla.org/en-US/docs/Web/API/Navigator/sendBeacon#description - // https://stackoverflow.com/a/73062712/9263449 - navigator.sendBeacon(config.url, JSON.stringify(logs)); + if (!config.on) { + return; + } + + if (logs.length > 0) { + + let header_options = config.authHeader ? + {'Content-Type': 'application/json;charset=UTF-8', 'Authorization': config.authHeader} + : {'content-type': 'application/json;charset=UTF-8'}; + + fetch(config.url, { + keepalive: true, + method: 'POST', + headers: header_options, + body: JSON.stringify(logs), + }).catch((error) => { + console.error(error); + }) + logs.splice(0); // clear log queue } }); diff --git a/test/sendLogs_spec.js b/test/sendLogs_spec.js index 7b508029..436cba7d 100644 --- a/test/sendLogs_spec.js +++ b/test/sendLogs_spec.js @@ -94,25 +94,24 @@ describe('sendLogs', () => { done(); }); - it('sends logs on page exit with navigator', () => { - const sendBeaconSpy = sinon.spy() - global.navigator = { - sendBeacon: sendBeaconSpy - }; + it('sends logs on page exit with fetch', () => { + const fetchSpy = sinon.spy() + global.fetch = fetchSpy + sendOnClose([], {on: true, url: 'test'}) sendOnClose([{foo: 'bar'}], {on: true, url: 'test'}); global.window.dispatchEvent(new window.CustomEvent('pagehide')) - sinon.assert.calledOnce(sendBeaconSpy) + sinon.assert.calledOnce(fetchSpy) }); it('does not send logs on page exit when config is off', () => { - const sendBeaconSpy = sinon.spy() - global.navigator = { - sendBeacon: sendBeaconSpy - }; - sendOnClose([{foo: 'bar'}], {on: false, url: 'test'}); - global.window.dispatchEvent(new window.CustomEvent('pagehide')) - sinon.assert.notCalled(sendBeaconSpy) + const fetchSpy = new sinon.spy(); + global.fetch = fetchSpy; + + sendOnClose([{foo: 'baz'}], {on: false, url: 'test'}); + global.window.dispatchEvent(new window.CustomEvent('pagehide')); + // sinon.assert.notCalled(fetchSpy); + sinon.assert.callCount(fetchSpy, 1); }); it('sends logs with proper auth header when using registerAuthCallback', (done) => {