Skip to main content

navigator.sendBeacon not firing when I close browser or tab

I am trying to send telemetry when my webpage is closed. Google and help on StackOverflow shows I should use navigator.sendBeacon

This is my effort

On my SPA page I have the following

document.addEventListener('visibilitychange', function logData() {
     if (document.visibilityState === 'hidden') {
         const data = telemetry.createObject(null, "End Session", {});
        telemetry.send(data);
     }
}

And this is the code it calls

const telemetry = new function () {

    this.send = function (telemetryObj) {
        const headers = {
            'type': 'application/json'
        };

        const blob = new Blob([JSON.stringify(telemetryObj)], headers);

        navigator.sendBeacon('/api/Telemetry/', blob);
    }

    this.createObject = function (popUpOrState, eventNameAsString, payloadAsJsonObj) {
    
        return {
            'eventName': eventNameAsString,
            'popUpId': popUpOrState,
            'sessionId': 'abc',
            'eventPayLoad': JSON.stringify(payloadAsJsonObj)           
     };
}

The code works fine if I call the telemetry.send(obj) direct, but doesn't execute when I close my tab or browser.

What have I done wrong?

Via Active questions tagged javascript - Stack Overflow https://ift.tt/DOpI8P3

Comments