Cancel redirect / beforeUnload - javascript

I'm using jQuery BlockUI plugin to display some nice ("Please wait...") message every time user changes URL, clicks link, is redirected, goes somewhere etc.:
$(window).on('beforeunload', function(){$.blockUI();});
Now, I'd like to enhance this message with a Cancel button, that would prevent such redirect and let user stay on current page. This leads me to a question: Is there any way in Javascript to stop URL change process, that is in progress? Or any other method/solution, that I could bind in this Cancel button's click event?
Am I trying to do something stupid or useless?

You could try e.preventDefault() or return false in the beforeunload bit but what you are wanting to do is not technically supported by browser for security reasons. Image the implications of an unclosable window...
The best thing to do is use the built in syntax. Returning a string to beforeunload pops up a dialog box asking if you are sure you want to quit, with that string as the question and the options "leave page" or "stay on page".
Example
$(window).on('beforeunload', function(){
return "Do you really want to leave this page?";
});
UPDATE
After further reading on this it turns out that major browsers support the return string syntax but Firefox does not. Firefox will simply replace your string with the line "Are you sure you want to exit this page?" or something like that.
TLDR: You can use the above return string syntax in all browsers but your custom sentence won't be shown in Firefox :)

Related

Leaving a page confirmation

I have this code which triggers when someone wants to press the back / forward button , close the browser and refresh the page...
$(window).bind('beforeunload', function(){
return 'Are you sure you want to leave?';
});
I don't want this to alert on reloading the same page otherwise it's ok.. And another thing is that which I don't know is how to catch the "Leave" button and "Cancel" button.
Help needed.
Thank You..
You can't know what page the user is navigating to (nor should you be able to).
You can only know which option the user chose by setting up a timed callback: If you get the callback, the user decided to stay on the page; if not, you know they didn't. Somethign along these lines:
$(window).bind('beforeunload', function(){
setTimeout(function() {
// They stayed, maybe
}, 250);
return 'Are you sure you want to leave?';
});
But I wouldn't be surprised if there were all kinds of browser compatibility issues doing that. In particular I'd test carefully on target browsers, in particular Firefox. Normally those prompts don't allow JavaScript code to run while they're showing, but...

How can I replace window.onbeforeunload with custom code?

For accessibility reasons, for my Chrome extension, I need to be able to replace all standard window.onbeforeunload popups with an in-page HTML substitute. I know how to create a substitute skeleton, that's trivial.
And I know the basic idea here is window.onbeforeunload = {my substitute code}.
What I don't know how to do is grab the text and code from each confirmation window that a page issues, and channel it into my substitute, so that the same message is shown as would be in the original popup and clicking my substitute confirm and leave page (or whatever) buttons yield the same result as the original popup.
How can this be done?
EXAMPLE:
You have my extension installed (don't ask what its purpose is, irrelevant).
You start writing a question on StackOverflow, then realize you already know the answer and go to close the tab.
Normally, a confirmation window would come up asking if you're sure you want to leave the page.
But because of my extension, instead, the whole page's HTML gets shoved down a bit to make room for a temporary HTML confirmation box is shown with the same text and the same two buttons that yield the same two results when clicked, all in-page. No pop-up.
The feature you're talking about is the window.onbeforeunload event, and unfortunately the only way it can be customized is to provide a custom string message for the user, because the potential for abuse is so high.
The api reference over at msdn for Internet Explorer states:
The default statement that appears in the dialog box, "Are you sure
you want to navigate away from this page? ... Press OK to continue, or
Cancel to stay on the current page.", cannot be removed or altered.
I take this to mean the dialog itself cannot be altered, all you can do is provide an additional context-specific message. I cant locate the same reference for Chrome, but it seems to be the same story there.
window.onbeforeunload = function() {
//all you can do is provide a message..
return "you have unsaved changes, if you leave they will be lost";
}

Handling Re-direct in Dirty Form

On my form, a user can modify it, i.e. make it dirty, and then click the Cancel button.
The Cancel button's onClick() behavior is to change window.location.
However, when I press the "Cancel" button, I notice that the window.location only changes if I click "OK" (IE8) or "Leave this Page" (FF or Chrome). But, if I click "Cancel" (IE8) or "Stay on this Page" (FF or Chrome), then the actual window.location does not change.
How does this work?
EDIT including code:
function (buttonPressed) { // called when Cancel button is pressed
window.location = ...;
}
As #マルちゃん だよ said, you can't force a redirect if the user doesn't allow it. It just won't happen. However, the question that needs to be asked is what your "Cancel" action does, and whether you actually need to use Javascript for it.
If you want the cancel button to reset the entire form, there are ways to do that, either
Using a button with type=reset, or
Using the form.reset function
Alternatively, if cancelling is meant to take the user to a different location, then while the words may say cancel, the button is actually submitting the form and relocating them. So, make the button a type=submit, capture the fact that the form was cancelled (maybe even store it so the user can return to it later), and redirect them server side to the right page. This has the added benefit that you can track how many users are cencelling, and working when Javascript is turned off or unavailable.
What you are asking for would be a major security breach. I'm afraid you will never be able to do that.
You can, however, have control over child windows the parent has opened. Say you opened a popup with a parent window, that same parent window can have a button to close the child. Never the main window.
As for the "Cancel" event on that confirmation dialog, you could always handle it:
window.onbeforeunload = function () {
if (confirm('Are you sure you want to leave this page?')) {
return; // allow user to exit without further annoying pop-ups
} else {
// Handle the Cancel event
// ...
return "Do you really, really want to Exit?"; // Make the browser ask for confirmation again
}
}
If the user does something to leave the page, then you can tell the browser to ask them if they are sure. You cannot silently prevent them. If the user wishes to leave the page, then they can do so (dodgy sites full of adverts and/or malware would love it to be otherwise, thankfully it isn't)

Onbeforeunload - windows assign doesn't work in Chrome

I'm trying to make "stay on page" button redirect to custom address. I found this code and it works in Firefox on OSX and PC, but in Chrome it doesn't do anything.
Am I missing something?
$(document).ready(function() {
window.onbeforeunload = function(){
location.assign('http://www.nba.com');
return "Play ball";
}
});
if a user wants to navigate away from your page or close the browser window then all you can do is either (1) Let Them [preferred] or you can (2) tap into onBeforeUnload event which is nothing more than an "are you sure?" pop-up message allowing the user to either stay on the page or not.
your code above that says return "Play ball" is what determines the message to display in the "are you sure?" dialog. if you don't return a string then you can execute clean up code before exiting without the user seeing the pop-up warning. chrome is smart not to let window navigation code execute before the return statement.
you should definitely NOT use onBeforeUnload for page redirection / site navigation.
if you post additional code and what you are trying to accomplish there is probably a better event for you to tap into.

Can I "redirect" user in onbeforeunload? If can't, how to?

Is it possible to redirect to another page when the user closes the browser?
Attempts:
I tried onunload, does not work
window.onunload = function redirect(){...}
I also tried another method, it doesn't work either:
window.onbeforeunload = redirect(){...}
<body onbeforeunload="return false; redirecty()">
The 3rd method, I want to cancel the onbeforeunload (means delay closing the browser), the I call the redirect function, window.confirm, if yes redirect, if no then close the browser. But it does not work as well.
Is there any other way?? Maybe prompt to let user select whether to redirect to new page when he/she close the browser? I'm running out of ideas...
Your onbeforeunload event needs to return a string (that doesn't equate to false), the browser will include this string in its own message displayed to the user.
window.onbeforeunload = function(){
location.assign('http://www.google.com');
return "go to google instead?";
}
However, it's going to be really tricky to word your message in a way that the user would be able to understand what to do. And I'm not sure this is robust in every browser, I just tried it in Chrome, it worked, but I ended up with a tab I could not close! I managed to kill it via the Chrome task manager thankfully.
It's not without it's faults but it works
window.onbeforeunload = function(){
window.open("http://www.google.com","newwindow");
return "go to google instead?";
}
This will open a new window as a popup to the address you selected when the user closes the page, though it is limited by any popup blockers the browser may implement.
If the user is trying to close the browser, then his intentions are pretty clear; he expects that the browser will close. Preventing that from happening, or causing anything else to happen in between the user clicking on 'close' and the browser closing is just a bad idea IMO. Is there a special reason for this? I mean, when I click on the 'close' button I expect that the browser will close, and should anything else happen, I would find that extremely annoying. I think I'm being reasonable enough. Am I? Who knows such things.
Why don't you try to entice the user to visit the other page in a less intrusive way? Like with a link or a banner?
The simple answer is no. If browsers allowed you to do more with the onbeforeunload/onunload events, this could be used pretty maliciously by anybody.

Categories