Rahul
Rahul

Reputation: 233

Prevent browser from closing in asp.net

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

Upvotes: 1

Views: 3569

Answers (3)

Giuseppe Accaputo
Giuseppe Accaputo

Reputation: 2642

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.

Upvotes: 0

mplungjan
mplungjan

Reputation: 178411

the code they use is

window.onbeforeunload=function() {
  if (somereasonorother) return "You did not save your stuff"
}

Upvotes: 2

DaveS
DaveS

Reputation: 3294

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;

Upvotes: 1

Related Questions