Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to detect if user pressed "Stay on page" or "Leave page" in beforeunload event?

Is there any way that I could detect in the following code that either user clicked "leave page" or "stay on page" button ?

$(window).on('beforeunload', function (){
    return "You save some unsaved data, Do you want to leave?";
});
like image 641
Umer Hassan Avatar asked Jul 20 '13 07:07

Umer Hassan


1 Answers

With a few hacks you can at least determine if the user stayed.
If the user left the page, there's not much you can do about that :

var timeout;

$(window).on('beforeunload', function (){
    timeout = setTimeout(function() {
        // user stayed, do stuff here
    }, 1000);
    return "You save some unsaved data, Do you want to leave?";
});

FIDDLE

like image 130
adeneo Avatar answered Oct 03 '22 14:10

adeneo