Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent closing browser window?

I tried the following code to get an alert upon closing a browser window:

window.onbeforeunload = confirmExit; function confirmExit() {   return "You have attempted to leave this page.  If you have made any changes to the fields without clicking the Save button, your changes will be lost.  Are you sure you want to exit this page?"; } 

It works, but if the page contains one hyperlink, clicking on that hyperlink raises the same alert. I need to show the alert only when I close the browser window and not upon clicking hyperlinks.

like image 352
user42348 Avatar asked Dec 02 '08 11:12

user42348


People also ask

How do I stop a browser window from closing?

Use the Pin tab option to keep Prevent Close available in Chrome. To make this as painless as possible, I recommend pinning this website to your browser then moving the tab out of the way. To do that open Prevent Close, and then right-click the tab with your mouse. From the context menu select Pin tab.

Can we disable browser close button?

No, you can't disable the close button on any web site. This would be a major security concern.

How to prevent window close in javascript?

Well you can use the window. onclose event and return false in the event handler. function closedWin() { confirm("close ?"); return false; /* which will not allow to close the window */ } if(window. addEventListener) { window.


1 Answers

Another implementation is the following you can find it in this webpage: http://ujap.de/index.php/view/JavascriptCloseHook

<html>   <head>     <script type="text/javascript">       var hook = true;       window.onbeforeunload = function() {         if (hook) {           return "Did you save your stuff?"         }       }       function unhook() {         hook=false;       }     </script>   </head>   <body>     <!-- this will ask for confirmation: -->     <a href="http://google.com">external link</a>      <!-- this will go without asking: -->     <a href="anotherPage.html" onClick="unhook()">internal link, un-hooked</a>   </body> </html> 

What it does is you use a variable as a flag.

like image 93
netadictos Avatar answered Sep 29 '22 11:09

netadictos