'JavaScript or ajax function when someone clicks on browser close button [duplicate]

I want to call a function when someone click on close button of browser. I gone through many posts and questions on Stack Overflow and Google groups. But couldn't find a way to accomplish this task. I want to send an ajax request when someone click on browser close button. Now I am using window.onbeforeunload JavaScript method but it is called each time when I click on a link or change web page.

window.onbeforeunload = function() {
alert("this method has been called")
return "Hey, you're leaving the site. Bye!";
};

But I want to call the method only on browser close button click. Is there any way by which I can catch browser close button clicked event? Help will be appreciated.



Solution 1:[1]

window.onclick = function() {
var win = window.open("/");
win.onload = function() {
    console.log("onload");
    win.onunload = function() {
        alert("Close onunload");
    }
}

}

Demo

Solution 2:[2]

$( window ).unload(function() {
  alert( "Handler for .unload() called." );
});

you can use this code

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nandakumar
Solution 2 Shaik Rilwan