7

I need to display a confirm dialog box before closing the browser window using javascript or PHP. The confirm box should come up when I click the close button of browser; otherwise, the dialog should not be displayed.

Thanks

Chad
  • 1,531
  • 3
  • 20
  • 46
user881851
  • 69
  • 1
  • 1
  • 4
  • 2
    possible duplicate of [Prompt User before browser close?](http://stackoverflow.com/questions/2923139/prompt-user-before-browser-close) – KooiInc Aug 06 '11 at 10:59
  • 3
    Please try searching SO before you ask a question. This question is answered several times. Try searching for *[javascript] dialog before close* – KooiInc Aug 06 '11 at 11:01

3 Answers3

12

This will display it when closing the browser:

window.onbeforeunload = function (event) {
  var message = 'Sure you want to leave?';
  if (typeof event == 'undefined') {
    event = window.event;
  }
  if (event) {
    event.returnValue = message;
  }
  return message;
}
Marcus Granström
  • 17,816
  • 1
  • 22
  • 21
4

Use this code , I used that earlier, I here

<html>
<head>
<title>.:I 0wn U:.</title>
<script language="JavaScript">
<!--
window.onbeforeunload = bunload;

function bunload(){
dontleave="Are you sure you want to leave?";
return dontleave;
}
//-->
</script>
</head>
<body>
Please stay on this page!
</body>
</html>
Govind Malviya
  • 13,627
  • 17
  • 68
  • 94
3

With Jquery:

$(window).bind('beforeunload', function(e) {
    // Your code and validation
    if (confirm) {
        return "Are you sure?";
    }
});
Justo
  • 1,793
  • 1
  • 10
  • 6