views:

60

answers:

3

Hi,

I am using asp.net 2.0 with c#.

i want a pop up to be displayed when user tries to close the browser and if user click on "no" [i.e. he don't want browser to be closed] then it prevent browser to get closed. Please help. Thanks

A: 

Pointy, this is entirely possible, and it's done by many web pages for perfectly reasonable reasons.

Try something like this:

function areYouSure() {
    return "Are you sure you want to leave this page?";
}
window.onbeforeunload = areYouSure;
DaveS
+2  A: 

the code they use is

window.onbeforeunload=function() {
  if (somereasonorother) return "You did not save your stuff"
}
mplungjan
PS: old but possibly still useful for you: http://www.4guysfromrolla.com/articles/101304-1.aspx
mplungjan
Wow ! :-)thanks a ton.
Rahul
You are welcome. Please note the other comments are valid too - if the user wants to leave they should be allowed to - and if your application is built on the need to know when they leave or close the browser, you may be in trouble :)
mplungjan
A: 

You can try to attach yourself to the onbeforeunload event:

<body onbeforeunload="ConfirmClose();">

But I have to mention that it won't work on all browsers. The only ones that prompted something after I closed a window were Chrome, Firefox and Internet Explorer; Opera ignored the code in the JavaScript method.

This is mostly because some browsers trigger the onbeforeunload event only when you're trying to leave the current page by visiting another one, and not when you close the current window / tab.

Giu
FF? https://developer.mozilla.org/en/DOM/window.onbeforeunload
mplungjan
It seems that I tried this one on an older version of Firefox; it works with the current Firefox release. I've now updated my answer; thanks for the hint
Giu