window beforeunload is not working as expected in jquery - javascript

Basically what i am trying to do was, whenever a user tries to close the current tab(when he was on my site), i want to display a pop up with three choices about why he was leaving and want to store that choice some where
So i have written the following in main.js which will be loaded through entire site pages
$(document).ready(function() {
// Before closing the current tab, ask user for a reason
$(window).on('beforeunload', function(event){
$('#load_choices_up').click();
event.stopPropagation();
event.preventDefault();
debugger;
});
});
So i have three issues with the above jquery code
*.This code was executing even when i click another link on the same page(I mean if i navigate to another page from current page), but i only want this code to run when the current tab/page was closed(about to close) completely, but not when navigating to another page on my site
*. After this line $('#load_choices_up').click() was executed, a choices pop up was opening as expected, but immediately the default processing of browser(that is closing functionality) was not being stopped with two lines event.stopPropagation(); and event.preventDefault();, i mean these two methods of stopping the behaviour is not working and the browser is closed, but i want to do some processing based on user choices input and then based on that i will close tab.
*. When i used return "Why do you want to leave the page", instead of choices pop up, the browser was displaying different message based on browser type like "You have unsaved changes" in chrome, and some different message in firefox, instead of displaying my custom message
So finally, why event.stopPropagation(); and event.preventDefault(); are not working ? and why i can't able to display my custom message ?

You can't prevent someone from closing the browser. This is for obvious security reasons. Imagine a spam-website preventing you from closing the website while pumping you full of god knows what.
You can at most pull one function like an alert() or a prompt. After a user closes them, the tab will close either way.
beforeUnload is also extremely short-timed. You won't be able to run massive scripts with it, as the user would probably close the tap before any script would run properly. (I tried it with an ajax call, didn't work)
So, even if you're able to get the options you want in there, the moment a user chooses one of the options, you're not going to be able to save it anywhere. Your script will never make it that far.
You can customize the "are you sure?" message like so:
$(document).ready(function() {
window.onbeforeunload = function(e) {
return 'Dialog text here.';
};
});
but again, you can only change the text. It's a browser's native functionality, and you cannot change it.

Related

Removing current page from browser history

I'm building a text editor in my website, the workflow is as follows.
In /list, the user picks an entry they want to edit from a list which takes them to /edit/[article_id].
The user does their work, and then clicks submit.
The server processes the thing, and redirects them back to /edit/[article_id] which by now reflects the edited work. The server also activates a flash message on the page to indicate the edit was successful.
By this point, the user probably wants to go back to /list and clicks the browser's Back button. This will take them back to the editor repeatedly depending on how many times they submitted.
I've tried putting a Back button somewhere on the page, but a good many users simply ignore it.
I'd rather not make the submission posted via AJAX, since that would also affect the flash message system.
What I like to do, is replace the last entry on the history list when the user submits, without changing its length. Is it possible?
Try this
window.location.replace(url);
after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Use window.close():
close();
Note: the current tab is implied. This is equivalent:
window.close();
or you can specify a different window.
So:
function close_window() {
if (confirm("Close Window?")) {
close();
}
}
with HTML:
close
or:
close
You return false here to prevent the default behavior for the event. Otherwise the browser will attempt to go to that URL (which it obviously isn't).

Switch/alert browser tab with JavaScript

I have a warning which users need to respond to on my site. Ideally I'd like to switch their tab in a similar way to how the alert() function currently does but without the alert popup.
If this isn't possible is there any way to make the tab flash to show a user response is needed?
One thing you could do to not spam the users watching your page/on your tab but work with your flow is this.
JavasScript
Function WarnUser ()
{
//If user isn't on this page alert them to problem.
if (!document.hasFocus())
{
alert("Warning!");
}
//Create pop up to deal with warning
}
I know this uses an Alert but your dialog would resolve the issue, the alert just brings them to the tab having a problem. Also with !document.hasFocus() it would only alert them when they are somewhere else which removes some of the redundancy.
Alternatively if a prompt dialog could resolve your warning that would also have a similar affect.

Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event?

Using Javascript is it possible to hook a custom function to the browser back button while preventing the default event?
So simply put, the user clicks the browser back button, and instead of being taken back to the previous page on my site, my function fires. My aim is not to to prevent the user leaving my site.
Something like the below pseudo code:
window.backbutton.click(function(e){ preventDefault(e); myFunc(); })
FYI What I actually have is an internal back/forward system controlled by buttons within the view and I'd like to trigger my buttons when user clicks browser back.
You should look into Browser History https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history . It is a new standard for emulating pages (back and forward) on a single-page site.
you can do this
$(window).bind("beforeunload", function() {
return "Are you Sure you want to do this even though there are internal navigation buttons? if you do whatever you have done so far
will be gone unless it has been completed and/or submitted "; //
Return whatever message you want
});​
Edit: this method displays a confirmation with the message and
automatically places buttons in the confirmation window
the author also clearly stated he does not want to prevent users from
leaving his site
see js fiddle http://jsfiddle.net/JW9fX/
Aaron - "updated question, I do not want to prevent them leaving my
site – Aaron 27 mins ago"
Edit: there is no definitive way to display a message only on the back
button in my knowledge i have also looked and have seen the only
methods that pick up on the back button are
$(window).bind("beforeunload",function(){return;}) and
$(window).onbeforeunload = function(){return;} and they both pick up
on when the page is refreshed or any other navigation away from the
current page. This is currently the best answer that can be provided
in the year 2014
Edit:
above is for all unload events
http://jsfiddle.net/Lhw2x/85/
been messing with that through all its lower objects it cant be done through javascript till someone decides to make all major browsers use a specific name for each unload event instead of it just being an unload event
so the answer is no you cannot hook a custom function to the browser back button while preventing the default event using javascript

IE11 alert after navigation begins cancels the navigation

We have some Javascript that is used for navigation when you click a tab in which the window.location is set to another URL with query string parameters. This URL basically:
checks if the user is logged in
If they are not, redirect them to an error page to login again
If they are, logs them out and continues to the next step
redirects them to another url of another system which then logs them in to that system
If the next system is taking some time completing the request, the browser is sitting there with the loading icon, and the user may get impatient and click the tab again. If they do, step 1 is done a second time, and now that they are logged out from the initial processing of step 1.2, they fail the check and end up following the path of 1.1.
The workaround we put in place is pretty simple. We put the window.location into an IF statement that checks if a person has already clicked on a tab and navigation has already been kicked off. If not, then it does the window.location setting. If so, then we call "alert('Please be patient');". This seems to work fine for every browser except for IE11, and even then, only when F12 dev console is not open. If you have it open, it works fine.
But if you don't, for some reason the alert popup ends up cancelling the navigation, and the page never goes anywhere. Almost the same as if you pressed escape, or clicked the "Stop" button. There's also sometimes this weird scenario where the next page loads, but it thinks that the alert window is still open, but it's not. I can see the extra task in task manager, but it's not visible.
Has anybody heard or seen anything like this? Please note, I know there are other ways of handling this situation other than using an alert. I'm not looking for suggestions about how to accomplish a message in a different manner. I'm more interested in finding out if there's any decent documentation that could explain to me why an alert after the page has started to unload may be behaving this way in IE11, and only when F12 isn't open.
EDIT Adding code Example
var navigatingTo;
function doNavigation(destination){
if (navigatingTo && navigatingTo != ""){
alert(navigatingTo);
} else {
navigatingTo = "Please be patient\nNavigating to " + destination;
window.location = "/somepage.aspx?d=" + destination;
}
}

Help required on onbeforeunload or click on browser back button

If a user clicks the browser's back button, then I want a prompt to appear and ask for confirmation. If the user clicks 'OK', then it should navigate to xx.html. If the user clicks 'Cancel', then it should prevent the navigation. How can I do this?
Note: Already I tried the onbeforeunload method, but it is working for all the navigation actions. For Example, clicking the link on the page will also fire this event and show the message to the user.
You can't. The best you can do is use onbeforeunload and remove that event when clicking on a normal link:
<script type="text/javascript">
window.onbeforeunload = function() {return "Are you sure?"}
</script>
Leave
There's no way to differentiate between navigational actions in the onbeforeunload event. You could disable it for all links/forms on the page by removing the window.onbeforeunload handler in each link's onclick handler, or onsubmit for forms. However, you will still be unable to tell whether the user clicked back, forward, a bookmark, etc or typed a new address into the address bar.
Firstly, you need to capture the "beforeunload" event (which previous answers here did).
// Display browser warning message when back/forward/reload or hyperlink navigation occurs
$(window).on('beforeunload', function(e) {
console.log('page navigation captured');
return 'By leaving this page you will lose the data you have entered here.';
});
More importantly, you want to allow non-disrupted navigation from certain elements (e.g. links with class "allow-navigation"). The way to achieve is to remove the event-handler when your links of choice are clicked.
// Disable capture for certain elements
$('.allow-navigation').on('click', function(e) {
$(window).off('beforeunload');
console.log('page navigation allowed');
});
Will work for your links of the type:
Click me
This way you can control the page navigation. Browser back/forward/etc still open the confirmation box. But the links you choose will work without any disruption.
Hope this helps.
you can do this
$(window).bind("beforeunload", function() {
return "Are you Sure you want to leave this page?"; // Return whatever message you want
});​
also if xx.html is the page in their history than you dont need to add
anything just return a message it will automatically put buttons for
you
Edit: see fiddle before you assume it does not answer the question
asked http://jsfiddle.net/Lxq93/
Edit: there is no definitive way to display a message only on the back
button in my knowledge i have also looked and have seen the only
methods that pick up on the back button are
$(window).bind("beforeunload",function(){return;}) and
$(window).onbeforeunload = function(){return;} and they both pick up
on when the page is refreshed or any other navigation away from the
current page. This is currently the best answer that can be provided
in the year 2014
Edit:
above is for all unload events
http://jsfiddle.net/Lhw2x/85/
been messing with that through all its lower objects it cant be done through javascript till someone decides to make all major browsers use a specific name for each unload event instead of it just being an unload event
so the answer is no you cannot force a navigation to a specific page when they click okay on the confirmation when they try to go to a different page
and back button does not have a specific event name it shares its event with several different events all in the unload event so you cannot make a back button specific function through javascript

Categories

Resources