Search code examples
javascriptreactjsevent-handlingonbeforeunload

How do I run code before user leaves the page?


Nothing I've tried does work. I need to run some code before the user leaves the page all:

window.onbeforeunload = function(){
   alert(1);
}

window.addEventListener("beforeunload", function(e){
   alert(2);
});

    window.addEventListener('unload', function(e) { alert(3); })

How am I supposed to do that nowadays? if matter, in the real application i'm using react and nextjs.


Solution

  • As an alternative to sending beacons (which my browser blocks by the way) you can catch the user as they move the mouse cursor out of the window and before they can kill the tab via...

    window.addEventListener('mouseout', (event) => {
    
    // do something here
    
    });
    

    Of course, the user may not necessarily kill the tab on leaving the window but there’s no harm in updating something when they do move away.