Onbeforeunload - windows assign doesn't work in Chrome - javascript

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.

Related

Cancel redirect / beforeUnload

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 :)

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)

How do I attach a Javascript event to the mobile Safari back button?

I need to show a confirm dialog box when the user clicks the back button in mobile Safari. I have a long application, and I want to alert users that their application has not been filled out/completed before they leave the page. I have everything set up for when the user clicks a link and tries to leave the page, but I can not for the life of me figure out how to attach an event to the browser's back button. onbeforeunload does not work in iOS. Any tips would be much appreciated.
NOTE: I realize alert boxes are the spawn of satan, but that's what I was told to do.
You can check the persisted property of the onpageshow event. It is set to false on initial page load. When page is loaded from bfcache (user navigates back with back button) it is set to true.
window.onpageshow = function(event) {
if (event.persisted) {
alert("From back / forward cache.");
}
};
For some reason jQuery does not have this property in the event. You can find it from original event though.
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
alert("From back / forward cache.");
}
};
In desktop browsers like Chrome you can intercept the leaving of a page and show a message.
And you can't do anything, except for showing the message. The browser is doing the rest, for obvious reasons.
Dunno if this also works on iOS.
window.onbeforeunload = function () {
return 'do you really wanna do that?'
}
http://jsfiddle.net/JAAZ5/
Control over the back button has never been allowed in any browser. I suspect mobile Safari is no different.

Customize onbeforeunload dialog box

I've got an onbeforeunload event working that pops up a dialog box warning users about unsaved changes to a form when they navigate away.
window.onbeforeunload = function() {
return 'You have unsaved changes.';
};
How do I customize the dialog box that shows up so it's a little more user friendly. Right now it's rather unwieldy:
"Are you sure you want to navigate away from this page?
You have unsaved changes.
Press OK to continue, or Cancel to stay on the current page."
I notice that Stack Overflow has one that is much cleaner: "You have started writing or editing a post", and the buttons say "Stay on this page", "Leave this page" instead of a generic "Cancel" and "OK". How can I do that?
I am using jQuery, if that's necessary for the solution.
Browsers don't let you customize this box at all. The only reason it would look different on SO is because you were using a different browser when you accessed it. Google Chrome uses buttons labeled 'Stay on this page' and 'Leave this page'. Based on the example text you posted, it looks like you tested your onbeforeunload handler using Internet Explorer.

JavaScript To Get An Alert To Redirect When Closing The Browser Window

I'm trying to get this JavaScript to work properly. My intention is, when a user is trying to close the site page to get an alert saying "stay on current page or close" If they hit 'ok' I want it to close, if they hit 'cancel' i want it to redirect to another page. The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing, not when leaving the page to another page. I'm not sure if that's possible, I do appreciate your help and comments.
window.onbeforeunload = fget;
function yPop(url) {
var found = 1;
window.onbeforeunload = '';
window.location = url;
return false;
}
function fget() {
alert("Thank you for visiting our website, you are welcome any time! \n\n");
window.location = "http://NewLink.com";
return "\n________________________\n\n PRESS 'CANCEL' To Stay On The Current Page \n\n________________________\n";
}
The problem is, when they try to go to another page on the same site, it gives them that popup. I want it to show only when closing
Don't do this.
You can't detect closing only, but you can tell the difference between leaving by clicking on an internal link and other kinds of leaving, including external links, back button, closing and choosing/typing a new URL. In a script after the page has loaded, set the onbeforeunload event, then scan over all the document.links and test their .host against the current location.host. If they match, it's an internal link. In this case add an onclick event to them that removes the onbeforeunload event before returning true, allowing the link to operate normally without a warning.
Seriously, don't do this. It is incredibly irritating, arrogant and useless. Webmasters who employ leaving-pester scripts are condemned to the the fourth circle of internet hell, where they must spend the rest of eternity making stylesheets work on Netscape 4 using only ed, a worn toothbrush and a < layer>-tag.
you should use the window onbeforeunload Event.
http://msdn.microsoft.com/en-us/library/ms536907(VS.85).aspx
https://developer.mozilla.org/en/DOM/window.onbeforeunload
for jquery users :
$(window).unload( function () { alert("Bye now!"); } );
You may want to consider building a "You're about to leave this site" page instead.
The idea is that you wrap URLs on the page that aren't on your site to point to that page, letting the visitor know they're about to leave, and giving them a chance to go back, or proceed.
It's gentler than an unexpected modal dialog, it lets you format your messaging better, and it ultimately gives your users the exact same choice.

Categories