How to control browser confirmation dialog on leaving page? - javascript

I know there are a lot of questions regarding this but nothing is answering me right. I want to show a confirmation dialog when user leaves the page. If the user press Cancel he will stay on page and if OK the changes that he has made will be rollback-ed by calling a method. I have done like this:
window.onbeforeunload = function () {
var r = confirm( "Do you want to leave?" );
if (r == true) {
//I will call my method
}
else {
return false;
}
};
The problem is that I am getting the browser default popup: "LeavePage / StayOnPage"
This page is asking you to confirm that you want to leave - data you
have entered may not be saved.
This message is shown in Firefox, in Chrome is a little different. I get this popup after I press OK on my first confirmation dialog.
Is there a way not to show this dialog? (the second one, that I did not create).
Or if there is any way to control this popup, does anyone know how to do that?
Thanks

Here's what I've done, modify to fit your needs:
// This default onbeforeunload event
window.onbeforeunload = function(){
return "Do you want to leave?"
}
// A jQuery event (I think), which is triggered after "onbeforeunload"
$(window).unload(function(){
//I will call my method
});
Note: it's tested to work in Google Chrome, IE8 and IE10.

This is simple. Just use
window.onbeforeunload = function(){
return '';
};
to prompt when the user reloads, and
window.close = function(){
return '';
};
to prompt when the user closes the page.
But the user have to click on the page once, or do anything on the page for the code to detect. You don't have to put anything the the return'';, because JavaScript interpreter would just ignore it.

window.onbeforeunload = function() {
if (data_needs_saving()) {
return "Do you really want to leave our brilliant application?";
} else {
return;
}
};

Related

Pop-up when leaving website

I've been asked to have a pop-up when visitors leave the site asking them if they really want to leave. This pop-up will only show if their shopping cart has items in it.
I can easily limit the pop-up to when the cart has items, however the issue I'm having is that even clicking an internal link loads the pop-up - how can I have it so this only comes up when actually leaving the site.
<script language="JavaScript">
window.onbeforeunload = confirmExit;
function confirmExit()
{
return "some message about leaving";
}
</script>
If a link is clicked, it will tell you in e.target.activeElement. You can check if it's a link there:
window.onbeforeunload = confirmExit;
function confirmExit(e)
{
var $element = $(e.target.activeElement);
if ($element.prop("tagName") !== "A") {
return "some message about leaving";
}
}
Note: You can add additional conditions checking $element.attr("href") to make sure it displays the message for links that aren't your site.
Alright first of all: Don't do this. Please. It's super-annoying for users. Just make sure the shopping cart items are stored on the server or in a cookie so users can always go back to the site.
Looking at this related question: How can i get the destination url in javascript onbeforeunload event? it can't be done easily.
Instead of using onbeforeunload, either attach a click handler to external links on your site that shows the popup, or attach a click handler to all links that checks if the link is external or not.
Again, don't do this...
You could get the URL of a clicked link item, and check if it's on the same domain. Put this in an if not statement, with the current code inside.
you'll have to control it to enable and disable the behavior, something like this:
<script>
var beforeunload = function (event) {
var message = 'some message about leaving';
(event || window.event).returnValue = message; // Gecko + IE
return message; // Webkit, Safari, Chrome...
};
document.addEventListener('click', function(event) {
if (event.target.tagName === 'A') {
window.removeEventListener('beforeunload', beforeunload);
}
});
window.addEventListener('beforeunload', beforeunload);
</script>
this is going to remove the beforeunload event whenever a link is clicked on the page.
One way, and again, I wouldn't recommend doing this either - the user should be able to leave your site without receiving a warning - but you could unregister the event if a link has been clicked:
$('a').click(function() {
window.onbeforeunload = null;
return true; // continue
});

How to disable browser feature

I am developing a project where user gets a conformation page. I want user not to click back or close tab or reload.
Now either I need to disable the browser features or get back button,tab close event, or reload event to java script so that I could take the needed steps to prevent my data to get lost.
I have used this:
window.onbeforeunload = function()
{
return "Try This";
};
But this get called even when I click a button that redirects the page.
If you just want to have the alert, understanding that the user is ultimately in control and can bypass your alert, then do what you're doing but use a flag that disables it when you're navigating and don't want the alert. E.g.:
var warnWhenLeaving = true;
window.onbeforeunload = function() {
if (warnWhenLeaving) {
return "your message here";
}
};
then in a click handler on the link/button/whatever that moves the user on that you don't want this to pop up on:
warnWhenLeaving = false;
In a comment you asked:
can i know that what user has clicked when alert is generated with this function. That is can i know what user has clicked (leave this page/stay on page)
The answer is: Sort of, but not really; you're almost certainly better off not trying to.
But: If you see your onbeforeunload function run, then you know the user is leaving the page and the browser is likely to show them your message. The browsers I'm familiar with handle the popup like an alert: All JavaScript code on the page is blocked while the popup is there. So if you schedule a callback via setTimeout, you won't get the callback if they leave and you will if they stay:
window.onbeforeunload = function() {
if (warnWhenLeaving) {
setTimeout(function() {
display("You stayed, yay!");
}, 0);
return "No, don't go!";
}
};
Live Example
So in theory, if you get the callback, they stayed; if you see an unload event, they left. (Note that there are very few things you can do in an unload event.)
I've tried that on current Chrome, current Firefox, IE8, and IE11: It works on all of those. Whether it will work in the next release of any of them is anybody's guess. Whether it works reliably on mobile browsers is something you'd have to test, and again could change.

jQuery Exit Popup Redirect?

So I've been looking around for hours, testing multiple versions, testing some of my own theories and I just can't seem to get it working.
What I'm trying to do is use alert or confirm (or whatever works) so popup a dialog when a user tries to navigate away from a purchase form. I just want to ask them "Hey, instead of leaving, why not get a free consultation?" and redirect the user to the "Free Consultation" form.
This is what I have so far and I'm just not getting the right results.
$(window).bind('beforeunload', function(){
var pop = confirm('Are you sure you want to leave? Why not get a FREE consultation?');
if (pop) {
window.location.href('http://www.mydomain/free-consultation/');
} else {
// bye bye
}
});
$("form").submit(function() {
$(window).unbind("beforeunload");
});
This is showing confirm dialog to user, want to stay or leave page. Not exactly what you looking for but maybe it will be useful for start.
function setDirtyFlag() {
needToConfirm = true; //Call this function if some changes is made to the web page and requires an alert
// Of-course you could call this is Keypress event of a text box or so...
}
function releaseDirtyFlag() {
needToConfirm = false; //Call this function if dosent requires an alert.
//this could be called when save button is clicked
}
window.onbeforeunload = confirmExit;
function confirmExit() {
if (needToConfirm)
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 taken from http://forums.devarticles.com/showpost.php?p=156884&postcount=18
Instead of using the beforeunload and alert(), I decided to check whether or not the users mouse has left the document. See code below:
$(document).bind('mouseleave', function(event) {
// show an unobtrusive modal
});
Not sure whether it will help.
You need to stop the propagation before showing the Confirm / Alert.
Please refer http://jonathonhill.net/2011-03-04/catching-the-javascript-beforeunload-event-the-cross-browser-way/
Look at the last comment.
Try this:
window.onunload = redirurl;
function redirurl() {
alert('Check this Page');
window.location.href('http://www.google.com');
}

Ask whether the user is sure to leave the site (XHTML/JavaScript)

When a user leaves one page of my website, there should be a warning message which gives the user the option to stay on the page:
"Are you sure that you want to close this page?"
It doesn't matter if the next page is an internal or external page.
I thought this could be done with the onUnload event handler, couldn't it?
<body onunload="confirmClose()">
The confirmClose() function must then show a message box with two buttons so that the user can choose between "Really leave" or "Stay".
function confirmClose() {
return confirm('Really leave this page?')
}
But this function can't stop the unload, right?
Do you have a solution for my problem? Thanks in advance!
You can only provide the text. The browser handles the dialog box (security reasons). Here is some code you can use:
window.onbeforeunload = function (e) {
var e = e || window.event;
var msg = 'Are you sure you want to leave?';
// For IE and Firefox
if (e) {
e.returnValue = msg;
}
// For Safari / chrome
return msg;
}
Try this out on different browsers, though. You'll notice the message should be constructed differently depending on the different browsers' dialog wording.
Here is what I use:
if (IsChrome) {
return 'You were in the middle of editing. You will lose your changes if you leave this page';
} else {
return 'You were in the middle of editing. Press OK to leave this page (you will lose your changes).';
}
You can add an onbeforeunload event. Note that it can only return a text string to include in the dialog the browser will display when the event is called. You can't tweak the dialog beyond that, nor can you trigger your own confirm as you're trying to do.
I'd note that this is very, very annoying behaviour except in a few specific situations. Unless you're saving me from significant data loss with this, please don't do it.
The browser takes care of displaying the confirm window.
You need to return the string with the message that you want to ask. Also, you may want to use onbeforeunload for cross browser compatibility.

How do I stop a page from unloading (navigating away) in JS?

Does anyone know how to stop a page from reloading or navigating away?
jQuery(function($) {
/* global on unload notification */
warning = true;
if(warning) {
$(window).bind("unload", function() {
if (confirm("Do you want to leave this page") == true) {
//they pressed OK
alert('ok');
} else {
// they pressed Cancel
alert('cancel');
return false;
}
});
}
});
I am working on an e-commerce site at the moment, the page that displays your future orders has the ability to alter the quantities of items ordered using +/- buttons. Changing the quantities this way this doesn't actually change the order itself, they have to press confirm and therefore committing a positive action to change the order.
However if they have changed the quantities and navigate away from the page I would like to warn them they are doing so in case this is an accident, as the changed quantities will be lost if they navigate away or refresh the page.
In the code above I am using a global variable which will be false by default (its only true for testing), when a quantity is changed I will update this variable to be true, and when they confirm the changes I will set it to false.
If warning is true and the page is unloaded, I offer them a confirmation box, if they say no they would like to stay on this page I need to stop it from unloading. return false isn't working, it still lets the user navigate away (the alerts are there for debugging only)
Any ideas?
onbeforeunload is the one you want; your function "should assign a string value to the returnValue property of the Event object and return the same string". Check the docs from Microsoft and Mozilla for details.
The string you return will be used by the browser to present the user with a custom confirm box, allowing them to refuse to stay there if they so choose. It has to be done that way to prevent malicious scripts causing a Denial-of-Browser attack.
This code warns as per Natalie's suggestion, but disables the warning if a form on the page was submitted. Uses JQuery.
var warning = true;
window.onbeforeunload = function() {
if (warning) {
return "You have made changes on this page that you have not yet confirmed. If you navigate away from this page you will lose your unsaved changes";
}
}
$('form').submit(function() {
window.onbeforeunload = null;
});
you want to use the onbeforeunload event.
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?";
}
window.onbeforeunload = function() {
if (warning) {
return `You have made changes on this page that you have not yet confirmed.
If you navigate away from this page you will lose your unsaved changes`;
}
}
Isn't supported in chrome, safari and opera
As said in this comment, nothing in jQuery binds to the beforeunload event.
#karim79: no it doesn't. There isn't anything in jQuery that binds to the beforeunload function; "unload" binds to the "unload" event. Search the source if you don't believe me ;-) – NickFitz
So you have to use pure Javascript to bind a function to the beforeunload event.
var warning = true;
$("form").submit(function() {
warning = false;
});
$('#exit').click(function() {
window.location.replace('https://stacksnippets.net/js')
});
window.onbeforeunload = function() {
if(warning) {
return true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<form>
<input type="submit">
</form>
Try using e.preventDefault() instead of returning false. 'e' would be the first argument to your unload callback.

Categories