2

Is it possible to catch browser close cross mark and ctrl w ??

I was trying with various thing as

// 1st option

 window.onunload = function (e) {
// Firefox || IE
e = e || window.event;
var y = e.pageY || e.clientY;

if (y < 0) {
alert("close");
}
else {
alert("refresh");
}
}

// 2nd option

<body onunload="myFunction()">

function myFunction()
{
    alert('sss');
}

// 3rd option

$( window ).unload(function() {

  alert('window unload');

});

But nothing has working for me (Measn these alerts weren't coming when i click on cross mark button on browser or used Ctrl + W )

Could anybody please let em know how to resolve this ??

Pawan
  • 31,545
  • 102
  • 256
  • 434
  • Could you detect the mouse going to the X? Idk, i don't think you can intercept browser actions with jQuery – Andy Holmes May 18 '15 at 15:45
  • is it possible with javascript ?? – Pawan May 18 '15 at 15:46
  • 1
    possible duplicate of [Warn user before leaving web page with unsaved changes](http://stackoverflow.com/questions/7317273/warn-user-before-leaving-web-page-with-unsaved-changes) – BSMP May 18 '15 at 15:48
  • possible duplicate of [javascript detect browser close tab/close browser](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser) – Hackerman May 18 '15 at 15:54

2 Answers2

3

Have a look at onbeforeunload:

var myFunction = function(e) {
    e = e || window.event;

    var message = "exit message";

    // For IE6-8 and Firefox prior to version 4
    if (e) 
    {
        e.returnValue = message;
    }

    // For Chrome, Safari, IE8+ and Opera 12+
    return message;
}
window.onbeforeunload = myFunction;
bitten
  • 2,463
  • 2
  • 25
  • 44
  • Thank you very much , This is my fiddle http://jsfiddle.net/p586bL44/ , how to avoid this popup initaily during page load (I mean i want this popup only when user wants to exit the browser .) – Pawan May 18 '15 at 15:54
  • 1
    I don't get this message when the page loads, only when I exit? It's also not necessary to include that body tag in there: https://jsfiddle.net/yb00ktc8/ – bitten May 18 '15 at 16:05
  • thank you , the only other issue i see that , the confirmation pop up is showing a different message than whats present in the function – Pawan May 18 '15 at 16:11
  • Could you provide a screenshot? – bitten May 19 '15 at 07:59
0
$(window).bind('beforeunload', function(e) {
    var message = "Why are you leaving?";
    e.returnValue = message;
    return message;
});

http://jsfiddle.net/XZAWS/308/

Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • Thank you is it possible to show this confirmation box only when the user tries to exit the browser – Pawan May 18 '15 at 16:02
  • @PreethiJain put it in a index.html file and you will see that it only pops up as the user closes the tab/browser – Miguel Mota May 18 '15 at 16:10