Way to Know If User Clicked Cancel on a JavaScript Onbeforeunload Dialog

Way to know if user clicked Cancel on a Javascript onbeforeunload Dialog?

You can do it like this:

$(function() {
$(window).bind('beforeunload', function() {
setTimeout(function() {
setTimeout(function() {
$(document.body).css('background-color', 'red');
}, 1000);
},1);
return 'are you sure';
});
});

The code within the first setTimeout method has a delay of 1ms. This is just to add the function into the UI queue. Since setTimeout runs asynchronously the Javascript interpreter will continue by directly calling the return statement, which in turn triggers the browsers modal dialog. This will block the UI queue and the code from the first setTimeout is not executed, until the modal is closed. If the user pressed cancel, it will trigger another setTimeout which fires in about one second. If the user confirmed with ok, the user will redirect and the second setTimeout is never fired.

example: http://www.jsfiddle.net/NdyGJ/2/

Detect if user did NOT cancel on a Javascript onbeforeunload Dialog?

Use the unload event. This event will be fired after they confirm the dialogue displayed because of the onbeforeunload event.

window.addEventListener("unload", function() {
console.log("Bye!");
});

Note that there are restrictions on what you can do in beforeunload and unload event handlers, to prevent malware that completely prevents you from closing the window/tab.

Is there a callback for cancelling window.onbeforeunload

There is no callback for staying on the page, but there is one for leaving the page, window.unload.

Try setting a timeout in beforeunload, then clear it in unload. If you stay, the timeout will run, otherwise it'll be cleared.

var timeout;

function warning() {
timeout = setTimeout(function() {
alert('You stayed');
}, 1000);
return "You are leaving the page";
}

function noTimeout() {
clearTimeout(timeout);
}

window.onbeforeunload = warning;
window.unload = noTimeout;​

DEMO: http://jsfiddle.net/aPwfz/1/

Record if the user clicked 'cancel' on Javascript 'beforeunload' event

You can use the unload event. Since most browser delete the log of a page once it's unloaded, I replaced it with a localStorage example.

function myfun(){
localStorage.setItem('myCat', 'Tom');
}

window.onbeforeunload = function(e){
e.preventDefault()
return 'Are you sure you want to leave?';
};

window.onunload = myfun;
if(localStorage.getItem("myCat")!=null)
alert("Last time this page was closed the unload event was called!");
localStorage.setItem('myCat', null);

Unload event will not always be fired, as Mozilla states :

Especially on mobile, the unload event is not reliably fired. For
example, the unload event is not fired at all in the following
scenario:

  1. A mobile user visits your page.
  2. The user then switches to a different app.
  3. Later, the user closes the browser from the app manager.

It's better to use visibilitychange event or pagehide event, even though they do not fully replace the unload event.

Also, the unload event is not compatible with the back/forward cache
(bfcache), because many pages using this event assume that the page
will not continue to exist after the event is fired. To combat this,
some browsers (such as Firefox) will not place pages in the bfcache if
they have unload listeners, and this is bad for performance. Others,
such as Chrome, will not fire the unload when a user navigates away.

The best event to use to signal the end of a user's session is the
visibilitychange event. In browsers that don't support
visibilitychange the next-best alternative is the pagehide event,
which is also not fired reliably, but which is bfcache-compatible.

If you're specifically trying to detect page unload events, it's best
to listen for the pagehide event.

How to know if we are leaving web page?

When a user changes the button position ON and then attempts to leave but then cancel, the state of the button should change to OFF. We can use window.onbeforeunload function and returning false within the block of its code. Please see the below example, note that I have used checkbox instead of toggle switch, but you can type anything inside the window.onbeforeunload function to your desire.

 window.onbeforeunload = () => {    document.getElementById("checkbox").checked = false;    return false;}
.checkbox {  margin-top: 20px;  margin-left: 20px;}
<p>Clicking the link below should prompt with "Leave" or "Cancel" option. If you check the box, then click on the link, and then click on "Cancel", the checkbox should return to false.</p>
<div> <a href="https://www.google.com">Click here to exit this site and go to google.com</a></div>
<div class="checkbox"> <input type="checkbox" id="checkbox"></div>

Detecting whether user stayed after prompting onBeforeUnload

What I ended up doing was hooking into the click event for my document, and once I received a click I considered the user had stayed.

It's not a good solution, in most cases (if you are a DiggBar) you'll have lots of false negatives (people will have stayed and you'll never know it), but in our case it made perfect sense, because people interact heavily with our site, not only with the framed sites.

Esentially, my code does this...

function OnBeforeUnload() {
Event.observe(document, "click", UserStayed);
if (IConsiderTheIFrameMightBeTryingToPopOut) {
return "The site is trying to escape. Do you want to stay?";
}
}

function UserStayed() {
Event.stopObserving(document, "click", UserStayed);
// New we know the user is still with us for sure.
}

Capturing result of window.onbeforeunload confirmation dialog

You can have the exit confirmation using window.onbeforeunload but there isn't a way to find out which button the user clicked on.

To quote an earlier response from jvenema from this thread:

The primary purpose for the
beforeunload is for things like
allowing the users the option to save
changes before their changes are lost.

Besides, if your users are leaving,
it's already too late [...]



Related Topics



Leave a reply



Submit