confirm before onbeforeunload

Nikita240 picture Nikita240 · Jul 26, 2013 · Viewed 9.7k times · Source

I need to prompt the user before he leaves the page, on confirmation close the tab and if not do nothing. I want to send an ajax call on onbeforeunload.

My only idea was to write handlers for both onunload and onbeforeunload like this:

window.onbeforeunload = function(){
    return 'Are you sure you want to leave?';
};
window.onunload = function(){
    $.get(
        "http://www.mysite.com/php/myhandler.php",
        { data: 1 }
    );
};

but this did not seem to work in jsFiddle

Answer

HIRA THAKUR picture HIRA THAKUR · Jul 26, 2013

It works fine in this fiddle--> Perfectly working fiddle!!!

 function warning(){
            if(true){
                return "You are leaving the page";
                 $.ajax({
                        url: "test.php",
                        type: "post",
                        data: values to send
                        })
            }
        }
        window.onbeforeunload = warning;