I need to "redirect" after clicking CANCEL onbeforeunload. So... On Before Unload, confirm appeared. If I click OK, the window will close, if I click CANCEL I'm staying on current page. So... I need after clicking CANCEL to redirect to another page. window.onbeforeunload = function(e) { e.returnValue="My custom message"; window.location="http://www.google.com"; }; Code (markup): The problem with this code is that "window.location" execute on before unload... when confirm appears. I need it to be executed after CANCEL clicked. Any solutions?
You could use a timer: window.onbeforeunload = function(e) { e.returnValue="My custom message"; window.setTimeout(function() { window.location="http://www.google.com"; }, 2000); }; Code (markup):
Currently, this code "don't work properly"... If I click cancel, it ask me again, and again... if I click OK... it redirects me to google.
Is there another event... that detects window close... not "native" url changing. Native url changing, I mean if somebody click on the link on the page... it is also onbeforeunload.
With timer does not work because of infinite loop... when redirecting... it is another "onbeforeunload"... if there is any other method to detect "window close", not window.unload... it will be better.
Hey I'm curious too. How about this: <script type="text/javascript"> //<![CDATA[ var is_asked = false; window.onbeforeunload = function (ev) { var e = ev || window.event; window.focus(); if (!is_asked){ is_asked = true; var showstr = "CUSTOM_MESSAGE"; if (e) { //for ie and firefox e.returnValue = showstr; } return showstr; //for safari and chrome } }; window.onfocus = function (ev){ if (is_asked){ window.location.href = "http://www.google.com"; } } //]]> </script> Code (markup):
really great work! I searched a day long to find this script for safari (firefox no problem). But can I stop this script when the user click on a link? For IE and Firefox I used this one: <head> <script type="text/javascript"> var exit=true; function confirmExit() { if(exit) location.assign('chance.php'); if(exit) return "Message Line 1\n\nMessage Line 2\n\nMessage Line 3\n\nMessage Line 4\n\nMessage Line 5\n\nMessage Line 6\n\nMessage Line 7\n\nMessage Line 8\n\nMessage Line 10\n\nMessage Line 11\n\nMessage Line 12"; } </script> </head> Code (markup): and in the body I used: <body onbeforeunload="return confirmExit()"> <center> <a href="http://....ic.php"><img src="http://....kt.gif" onclick="exit=false"></a> <a href="http://....kt.php"><img src="http://....rb.gif" onclick="exit=false"></a> <a href="http://....in.php"><img src="http://....se.gif" onclick="exit=false"></a> </center> Code (markup): How can I do this in Safari/Chrome? Thanks for help! Greetings
window.onbeforeunload = function(e) { e.returnValue="My custom message"; window.setTimeout(function() { window.location="http://www.google.com"; }, 2000); };