My problem is a bit more complex than using the following simple JavaScript code:
window.onbeforeunload = function (e) {
return 'Are You Sure?';
};
On an e-commerce web page I would like to remind the user that he has items in the shopping cart so that he can change his mind before
closing the browser tab/window
navigating to another domain
The JavaScript method above does not solve my problem because it is evoked even when the user navigates within the domain.
Short:
User tries to close window -> Show dialog
User changes www.mydomain.com/shoppingcart url to www.google.com in the browser's address bar -> Show dialog
User navigates to www.mydomain.com/checkout with the checkout button or presses the back button in the browser -> Do NOT show the dialog
It's not possible to tell if a user is pressing the back-button or closing the tab and you don't have access to their intended location.
It is possible to stop the dialog from showing if an internal link is clicked though:
(function(){
function isExternal( href ) {
return RegExp('https?:\\/\\/(?!' + window.location.hostname + ')').test(href);
}
var returnValue = 'Are you sure?';
document.documentElement.onclick = function(e){
var target = e ? e.target : window.event.srcElement;
if (target.href && !isExternal(target.href)) {
returnValue = undefined;
}
};
window.onbeforeunload = function(){
return returnValue;
};
})();
Sorry there's no technical solution to your "problem."
It's not an accident when a user decides to leave your site, i.e. by typing a new URL, so stopping them to say "Hey, you haven't checked out yet" is kind of pointless.
I would suggest letting the visitor leave your website freely and simply remembering their information (DB, Sessions vars, etc). In terms of eCommerce that is the polite way of keeping customers.
If someone wants to leave your website, they will. Double-checking beforehand will likely only irritate the customer and lessen your chance of their return.
Since the beforeUnload-event object does NOT contain the location the user is trying to go to, one "hack" to do this would be to add click listeners to all links on your site, and disable the unload-listener in that handler. It's not very pretty, and it will probably not work if the user navigates with the keyboard, but it's my best guess at the moment.
It sounds like you'd need to use an onbeforeunload and then modify all your internal links to disable it. Probably the thing to do for the latter would be a jQuery event; making the actual hrefs run through JS would be terrible, not least because it'd defeat search engine crawling.
I was looking into this too, reason being we have some really stupid end users who fill out a whole web form then don't press the save button.
I found this is u r interested, seems like a good solution:
https://web.archive.org/web/20211028110528/http://www.4guysfromrolla.com/demos/OnBeforeUnloadDemo1.htm
Related
I have found on StackOverflow this script that handles the issue when a user wants to leave the page, to ask him before doing it.
ISSUE
It is working fine (even though there is probably a much better solution) but I have realized that it is causing one "bug". When a user sends data from the form and the script asks him does he want to leave the page (because of the redirect) it still sends data. So, even if the user clicks on "Cancel" it will still proceed to the store() method and if the user adds something more and sends again the data I get duplicates. Is there a way to include "stop propagation" in this script?
CODE
window.onbeforeunload = function () {
return 'Are you sure you want to close this website?';
};
Additional question
Since this script is running with the Laravel Livewire, every time I click on any button related to the livewire (which won't redirect the user to the other page) script prompts the popup to ask if the user is sure he wants to leave the page. Is there any workaround (if you need some other code, write a comment because I am not sure which part could help you at all :) ) for this issue?
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle
www.example.com/templates/create-template
I want to warn users if they leave create-template page. I mean whether they go to another page or to templates.
I use this code to warn users on a page reload and route changes should the form be dirty.
function preventPageReload() {
var warningMessage = 'Changes you made may not be saved';
if (ctrl.templateForm.$dirty && !confirm(warningMessage)) {
return false
}
}
$transitions.onStart({}, preventPageReload);
window.onbeforeunload = preventPageReload
It works as expected on a page reload and route changes if it is done by clicking on the menu or if you manually change it. However, when I click the back button, it does not fire the warning. only it does if I click the back button for the second time, reload the page, or change route manually.
I am using ui-router. When you click back button, you go from app.templates.create-template state to app.templates state.
How to warn if they press Back button?
First of all, you are using it wrong:
from https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload:
Note: To combat unwanted pop-ups, some browsers don't display prompts
created in beforeunload event handlers unless the page has been interacted
with; some don't display them at all. For a list of specific browsers, see the
Browser_compatibility section.
and
window.onbeforeunload = funcRef
funcRef is a reference to a function or a function expression.
The function should assign a string value to the returnValue property of the Event object and return the same string.
You cannot open any dialogs in onbeforeunload.
Because you don't need a confirm dialog with onbeforeunload. The browser will do that for you if the function returns a value other than null or undefined when you try to leave the page.
Now, as long as you are on the same page, onbeforeunload will not fire because technically you are still on the same page. In that case, you will need some function that fires before the state change where you can put your confirm dialog.
How you do that depends on the router that you are using. I am using ui-router in my current project and I have that check in the uiCanExit function.
Edit:
You can keep your preventPageReload for state changes in angular. But you need a different function for when the user enters a new address or tries to leave the page via link etc.
Example:
window.onbeforeunload = function(e) {
if (ctrl.templateForm.$dirty) {
// note that most broswer will not display this message, but a builtin one instead
var message = 'You have unsaved changes. Do you really want to leave the site?';
e.returnValue = message;
return message;
}
}
However, you can use this as below:(using $transitions)
$transitions.onBefore({}, function(transition) {
return confirm("Are you sure you want to leave this page?");
});
Use $transitions.onBefore insteadof $transitions.onStart.
Hope this may help you. I haven't tested the solutions. This one also can help you.
I'm wondering if there is any solution in JavaScript or JQuery to show the message to the user if they want to close their browser/window? I know there is an option to use beforeunload but the only problem is that I couldn't find what user selects Leave Page or Stay on Page. Reason why I'm asking if this is possible is because if user selects Leave Page I want to process AJAX call and then close the browser. All solutions so far would run AJAX call before user selects the option. Here is example of my current function that I use:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "Your browser is now offline.",
recID = $.trim($("#recordID").val());
recID ? removeLock(recID) : ""; // Call function to remove record from the Lock table.
(e || window.event).returnValue = confirmationMessage; //I'm not sure what is the purpose of this line ???
return confirmationMessage;
});
As you can see above in the code my removeLock() function will execute as soon as user clicks on the X to close the browser/window. That will remove record from the lock table. This can be the problem if user decides to stay on the page. I'm wondering if there is any alternative solution or the way to check what user selects? Thank you.
I read your post as this may come in handy for tracking user behaviour one day.
I think your question is answered in an older post:
Capturing result of window.onbeforeunload confirmation dialog
HTH
i want disable browser back button and refresh button. in angular
example my source
page source :
"use strict";
.controller("wizardSecondController", function($scope, $state, $stateParams, wizardManager) {
$scope.$on("$viewContentLoaded", function(event, data) {
});
i want prevent browser back and refresh .
please answer .
If you want to disable browser back button in angular, please try out the following code. It may help.
$scope.$on('$locationChangeStart', function(event, next, current){
event.preventDefault();
});
It's not a very straight forward thing in Angular.js but you can use JavaScript function - window.onhashchange to disable to back button.
Take a look at this link, you might get better ideas.
Use javascript event
window.onbeforeunload = function(e) {
var dialogText = 'Dialog text here';
e.returnValue = dialogText;
return dialogText;
};
refer
I shall give you advice as to disabling the back button:
Strictly speaking it isn't "possible" if using standards, but there are workarounds.
There is the window.history object which includes a small API.
But it doesn't allow you to double check for states/pages before the user surfed to your site. Obviously for security reasons and not by accident or missing implementation.
There's various checks for the usage of navigating back in the history and several posts about that topic, but none is helpful as to when it comes to the point the user leaves your page and goes beyond your accessible history.
As to that, check on the events
onhashchange
onpopstate (be aware IEs implementation thereof is half-baked, even in IE11 --> in my case it didn't respond to mouse interaction, only to js history.*()
If you want to catch the user on your site for some hopefully incredibly good purpose:
Create a duplicate entry of your home page on the first homepage-hit via window.history.pushState and instantly window.history.forward() --- (this works especially well and unnoticable on SPAs)
Reiterate that procedure every time the user navigates to your homepage/lowest_level_parent_state ...
Et voila ...
In my case I can't even escape our page if I hold down the backspace button ...
Another convenient option would be to put the page into fullscreen mode if feasible :)
Cheers, J
I've got a problem about onbeforeunload recently that I need to pop up a voting page when users try to close their IE browsers.I did it by using:
<body onbeforeunload="makevote()">
And the main structure of makevote() in javascript is as follows:
function makevote()
{
comet.distruct();
if(csid != null && isvote == null)
{
window.event.returnValue = false
window.event.returnValue='press “cancel” to vote please!'
showComDiv(popvote,"popiframe",400,120,'your vote here','dovote()');
}
}
In last three months this voting function performed so ugly that I got only less than 8,000 votes from more than 4,50,000 vistors.I think the problem is, when the users try to close their browsers,the onbeforeunload property pops up a comfirm box which covered my voting box while most users click the OK button,which means close comfirming is done,as a habit.So my question is how can I control the comfirming box made by onbeforeunload myself? For example if I click the "OK" ,I'll go to the voting box instead of closing my IE.So far what I can do is only defining the message it shows.And is there any other better way to do this?Help would be greatly appreciated!
Regards
Quite simply, you can't.
This is built-in behaviour, designed to only allow very minimal changes for security purposes. It's the same in every browser; FF, Chrome, etc, all will behave the same way.
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 - they won't want to answer a survey anymore, they're done!