Skip to content

Commit

Permalink
Updated sendOnClose() to use old school catch() with async fetch()
Browse files Browse the repository at this point in the history
  • Loading branch information
rthenhaus committed May 14, 2024
1 parent c28f3e3 commit bcd16ec
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 20 deletions.
26 changes: 19 additions & 7 deletions src/sendLogs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
});
Expand Down
25 changes: 12 additions & 13 deletions test/sendLogs_spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down

0 comments on commit bcd16ec

Please sign in to comment.