How can I write a function that will display an alert when the user tries to leave the page?
I've been thinking about a 1px high div at the very top of the website, and when the user hovers it an alert appears, but I can't place it there, the less html code I place for this purpose the better.
Another method I've been thinking of is unload, or beforeunload events, but they seem to be deprecated.
How can I do this?
How can I write a function that will display an alert when the user tries to leave the page?
The only way to do that is to use onbeforeunload, and you get very little control: Basically, you can supply a message which will probably (but only probably*) be shown to the user. The user will get two choices: Go ahead and leave, or stay.
onbeforeunload is a very unusual event. Here's how you hook it:
window.onbeforeunload = function() {
if (youWantToShowAMessage) {
return "The message goes here.";
}
};
Another method I've been thinking of is unload, or beforeunload events, but they seem to be deprecated.
I'm not aware of either of those being deprecated. What you can do in them is very restricted (for good reason), but until there's a replacement, onbeforeunload serves a useful purpose: It lets the web page tell the user they may be losing something (e.g., unsaved work) when they leave. The current mechanism which only allows a message and very, very few other actions is a decent one: It puts the user in control, but lets the page be useful.
* Mozilla has flirted with just showing a generic message, not showing your message.
Related
How to make it work, couse now it won't work. I want to auto click button if detect website close.
<script>
function myFunction() {
document.getElementById("makeOffline").click();
}
</script>
<body onbeforeunload="return myFunction()">
That will call your function. But the things your function is allowed to do, in a modern browser, are very limited. You can't, to pick a random example, submit a form.
In general, the only useful use case for onbeforeunload is to warn users that they may lose data if they leave the page, which you can do by returning a string from your handler. The browser will then check with the user to see if they really want to leave (most of them will show the string you return, but not all — Firefox doesn't anymore, for instance).
Anything else you might be trying to do in an onbeforeunload handler is almost certainly better suited to being done some other way. If you post a question about your end goal, people may be able to help you with it.
I have a scenario where I need to capture the response received from a dialog box INVOKED by IE from an onbeforeunload event handler. The dialog box is a familiar one,
"Are you sure you want to navigate away from this page? You will lose any unsaved modifications to this document. Press OK to continue or Cancel to stay on the current page."
I will emphasize for the sake of anyone misinterpreting this question, that the dialog box I am interested in capturing is THE BROWSER's dialog window, NOT a dialog window that one might create using a third party library such as JavaScript, Telerik or etc. as the source.
I am really not that concerned with capturing a click of the OK button (although it would be a plus) but more concerned with the clicking of the Cancel button because it requires more than simply retaining the user on the current page and our company would like to implement some additional logic on click of the Cancel button.
I believe I have diligently searched all resources available inclusive of Stack Overflow but I cannot find any specific answer or information regarding how to acquire the handle on the dialog and determine which button the user clicked.
Since our companies primary browser for this application is IE, the question is only with respect to IE. Can this be done and if so, where might I find the appropriate documentation or acquire a lead? Seeing as I haven't found any definitive answer to date, I am presuming it is not possible but would like others responses to this.
EDITED:
This question is specific to acquiring the users input (Using IE's Native Dialog or the Browser's native prompt). E.g. Again, Not Dialog boxes or Prompts developed by (You) as the Developer.
NOTE: --> There is a very significant difference in that developing with a Third Party library you as the Developer already have a reference to the object because YOU create it. Whereas you don't have an obvious handle to a Dialog Box created by the Browser.
You can't actually get the result of what was clicked, but you can use setTimeout in your onbeforeunload event to run some code if the user chooses to stay on the page.
For example:
var afterStayFunction = function() {
$("body").append("Thanks for staying.");
};
$(window).on("beforeunload", function(e) {
var prompt = "Are you sure you want to leave?";
e.returnValue = prompt;
setTimeout(function() { afterStayFunction(); });
return e.returnValue;
});
Live example here
I am supporting an e-commerce app, which pretty much makes and submits orders.
A user found that if they submit their order, and press back really quickly, they can cause an error condition.
I want to prevent this. When the user clicks submit, I want to bind some kind of event to the browser's back button that instead will redirect them to the Index page. However, after about two hours of Googling (including a few StackOverflow topics), I have not found any clear way of influencing the behavior of the back button.
I briefly attempted to use history.pushState(), but as the HTML 5 documentation mentions, that will not cause a redirect; it merely alters the displayed URL/state.
Similarly, the history.onpopstate event appears unhelpful, because it occurs whenever a state is removed from the history listing; I'm looking for an event that occurs whenever the history listing is traversed backwards.
Question: Does an event for the browser's back button, or at least a way to prevent this particular stupid user trick exist?
You can't listen to the browser back button because it's outside of your reach (it's not part of the DOM).
What you can do is fix the previous page so that it detects if you've used the back button.
Without more information I can't give you any tips on how to achieve that.
Also, an error condition is not necessarily a bad thing. Just make sure it's clear what is happening: the error message should make sense.
Wrong answer...
Instead listen to window.onBeforeUnload and ask the user if he knows what he is doing. Return false if not. This is usually done via a confirm dialogue
I'm looking to implement a warning if the user attempts to leave the order process before it's completed in any fashion other then of course following the payment button.
Something like this:
<script type="text/javascript">
window.onbeforeunload = function(){
return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
};
if document.getElementsByClassName('eStore_buy_now_button').onclick = function(){
};
</script>
I'm sure that's detrimentally wrong in a few ways, but it's the best way I can illustrate what I'm trying. And I understand some browsers will display default text instead of the actual warning I've written, that's fine.
A few notes, I'd rather use plain old JS instead of loading up jQuery for just this one simple task. There are no settings on the page so it's a simple leave page or click "Buy Now" operation.
UPDATE:
I assure you it's not for my sake, it's for the user's sake. Although it's explicitly explained (what to do), I think user's are jumping the gun and leaving before the process is truly finished out of an instant gratification, ignore the messages kind of mentality. It's a simple 2-step process, they submit the details for the project and then make payment. For whatever reason they're submitting details and then not following through with payment about 50% of the time. And then they'll follow up "So, are you working on the project or what?" and then I have to explain "You never finished your order." They follow up with a "Whoops, here ya go."
Unfortunately, I would chalk this up as marketing and web design 101. Rule #1, people are dumb. Not to be taken in a rude or pessimistic sense. Basically, the idea is assume everyone is dumb in your design, instruction so that you make something so easy a five-year-old can do it. I totally agree with not holding users hostage. But this page is ONLY reached in the middle of their intended order process that THEY initiate (this page will never be reached in a browsing sort of way). So I think it's a pretty legitimate use case where you're saving a common user mistake from themselves. A demographic of customers that are not tech-savvy, so they honestly need such guidance.
document.querySelector('.eStore_buy_now_button').addEventListener("click", function(){
window.btn_clicked = true; //set btn_clicked to true
});
window.onbeforeunload = function(){
if(!window.btn_clicked){
return 'You must click "Buy Now" to make payment and finish your order. If you leave now your order will be canceled.';
}
};
This will alert the user whenever the page unloads (eg leaving the page) until btn_clicked is set to true.
DEMO: http://jsfiddle.net/DerekL/GSWbB/show/
Don't do it.
There is a fine line in terms of usability - on one hand sometimes I may have intended to place an order but accidentally left the page; on the other hand it could get annoying pretty quickly. When abrowser is set up to save previous session (i.e. reopen tabs on next launch) and one page behaves this way, you'll end up with only that tab re-opened next time (confirmed on Mac Safari), discarding the rest of the tabs. They'll not be buying from you again!
I'd suggest you make it clear to the user by means of inline messages that the order has not been submitted yet and they still need to confirm their action, but if they were to accidentally navigate away you should make it easy to pick up where they left off. Would be fairly trivial to store such info in a cookie so that on subsequent page visits the user would be prompted with "you have an incomplete order for ..., would you like to finish it now?"
As an alternative, you could use rely on an inactivity alert (think of online banking prompting you when your session is about to expire) to bring the user back to the "complete order" page if they get distracted.
If you are certain you want to rely on this event, the answers to this question may provide better insight. Basically, the functionality or its implementation beyond a basic text warning should not be relied onto because of inconsistent (?) implementation across browsers as well as possibility of having it blocked by the user.
Another update:
Prompted by Derek's comment on this approach being used by Gmail etc., I've come across an article suggesting you stick with onunload instead and rely on AJAX calls to save the state of the page - which backs my thoughts on allowing the user to pick up where they left even if the javascript event is never triggered.
I am creating my own simple stats to record which pages were read and for how long etc.
I then use an ajax call to record the info in a database, it's working using the window.ONBEFOREUNLOAD event, however this creates a database record for each page visited and instead I want to save the page stats to js variables and then only do 1 ajax call when the visitor finally leaves the site.
Is there a way of creating an event listener using pure javascript to detect when the user leaves the site, maybe by evaluation the body's click event ???
No.
It is not possible for a browser to provide such an event by default: the browser itself has no awareness of what encompasses an entire site, it's thus impossible for a browser to know when a user leaves a site.
It is easy implement a solution yourself in JavaScript. The implementation is easy, the solution is hard.
You need to consider how you can tell when a user leaves your site. How do you define exit points? Can you define exit points? This is a non-trivial problem. I am not certain a solution exists.
Method 1:
Try the onbeforeunload event: It is fired just before the page is unloaded
It also allows you to ask back if the user really wants to leave.
see this demo
alternatively, you can send out an ajax request when he leaves.
Method 2 :
`if(window.screenTop > 10000)
alert("Window is closed");
else
alert("Window stillOpen");`
Method 3 :
See this article.
The feature you are looking for is the onbeforeunload
sample code:
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
</script>
All information in this answer are found on StackOverflow.com