JS: Send raygun message before unload of page

Joacim Boive

Posted on
Apr 21 2015

<script>
    Raygun.init('mykey',{
        allowInsecureSubmissions: true,
        ignoreAjaxAbort: true,
        ignoreAjaxError: true,
        debugMode: true,
        ignore3rdPartyErrors: true,
        wrapAsynchronousCallbacks: true
    }).attach();
</script>
<script>
    $(window).on('beforeunload', function(){
        try {
            // your code
            throw new Error('Test message');
        }catch(e) {
            Raygun.send(e);
        }finally{
            return;
        }
    });
</script>

I wish to send a message when the page is unloaded/closed. But all I get in the network tab of Google Chrome Dev Tools is: status: (canceled)

And nothing is sent.

I suppose it's because Raygun hasn't been allowed to finish its POST before the page moves on to the next.

Anyway to get around this? I can't post a message so the user has to press OK. The solution has to be transparent to the user.

Thanks!

/J


Callum

Posted on
Apr 22 2015

Hi Joacim,

The browsers have implemented this behavior to prevent pages blocking on unload, causing it to look like the tab has hung and resulting in undesirable UX. The recommended approach and the design of the beforeunload event is to use Gmail's approach, where you return a string from that event's callback:

$(window).on('beforeunload', function() {
    return 'Cancel?';
});

With the way the APIs work today, the implication is that there's no way for this case to be transparent to the user - either we prompt them a dialog, or hang the browser while the request completes (time not guaranteed, especially on bad/mobile connections).

The classical way to get around this was to set 'async' to false on the XHR object, and this currently works in IE, but doesn't appear to do so any more in Chrome (the request stays as 'pending' in the network tab), and Firefox has apparently deprecated synchronous behavior on the main thread for the reasons above. As such you'd only reliably receive notifications for IE users.

I did find one report where you return a string (technically a number) at the end of your beforeunload callback. This makes the dialog and seemed to give the browser time to complete the ajax request, might be worth a try:

$(window).on('beforeunload', function(){
        try {
            // your code
            throw new Error('Test message');
        }catch(e) {
            Raygun.send(e);
        }
        return 'prompt';
    });

Reply