jQuery Exit Popup Redirect? - javascript

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');
}

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 control browser confirmation dialog on leaving page?

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;
}
};

How to stop unloading the page?

I have a page where user needs to enter some data and click save to validate the changes, but my problem is if the user is trying to close the browser window or click on a different link to navigate to a different page..I need to delete all the entries the user has saved so far..
I am doing it the following way
window.onbeforeunload = function()
{
if(confirm('Are you sure you want to navigate'))
{
//Invoke `enter code here`server side method
}
else
{
// return false;
}
}
Everything works fine if he click on Yes, the problem comes when he click on "No"..Even if he click on No..the page unload method is getting called and it is redirected to a different page..but I want it to stay in the same page in same state...can you please help me in achieving this.
Thanks and appreciate your response....
You cannot stop the user from leaving the page. What you can do is alert a message to them, asking if they want to leave or not.
The window.onbeforeunload event should return a string (and only a string). This string will be printed on the alert box made by the browser.
You cannot use your own alert box, or block the user from leaving (or redirect them).
window.onbeforeunload = function(){
return 'Are you sure you want to leave?';
};
Or with jQuery
$(window).on('beforeunload', function(){
return 'Are you sure you want to leave?';
});
When a user leaves the page, you can use the onunload event to make an AJAX call (you may need to use async: false here).
Example:
$(window).unload(function(){
$.ajax({
url: '/path/to/page/',
async: false, // this may be needed to make sure the browser doesn't
// unload before this is done
success: function(){
// Do something
}
});
});
NOTE: Instead of doing this, why don't you just save everything when the user is completed? Instead of saving it and then removing it if the user doesn't finish?
First of all: you can't! It's impossible. onbeforeunload only accepts a string as return value and will then close if the user wants that.
But then think about what happens if the computer is being without energy and shuts down? Or the browser will closed by the Task Manager? Or even more "realistic": The internet connection get lost! => Then you got invalid data states too!
You are trying to solve a false problem! Your problem isn't this function, your problem is the state of your formular!
Why do you need some kind of function? Do you saving the data before he clicks on save? Then don't! Or make sure to have another query which detects unfinished data in your database and delete it after a timeout!
onbeforeunload only accepts a string as return value. That string will be displayed by the browser with the option to stay on the page or leave it. But that's ll you can do.
You can use something like this, just call the following function on your page
function noBack() {
window.onbeforeunload = function(){window.history.forward()}
}
this disables Back button if window.history is clean, otherwise it works only first time.

Gmail-style Exit Message

I realize this is likely a duplicate, but I've been googling/SOing for a day now and I can't find a satisfactory answer. If there is an answer already on SO, please send me there.
I have a client that insists on having an exit message popup confirming they want to exit the site, just like Gmail does. (I've already tried arguing against it. He is immovable, so no comments about how that is bad practice please.)
I've found this code:
<script>
window.onbeforeunload = function() {
return 'Are you sure you want to exit?';
}
<script>
But it runs no matter what I do - reloading the page, clicking on the nav, etc.
I just want the message to show up when the user closes the tab/browser. I suspect it's something simple I'm missing but I'm not a Javascript expert.
Any help would be greatly appreciated.
Thanks
EDIT
Here's what is working pretty good. Thanks to all!
var isLeavingSite = true;
//This would be called on each link/button click that navigates
$('a, input[type="submit"]').click(function(){
isLeavingSite = false;
});
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
Though it could be a fair amount of work (depending on how your site is written), you could do something like this (pseudo-code):
var isLeavingSite = true;
//This would be called on each link/button click that navigates
function GlobalLinkHandler()
{
isLeavingSite = false;
}
window.onbeforeunload = function() {
if(isLeavingSite)
return 'Are you sure you want to exit?';
}
If you're using jQuery, you can use the code below to flip the isLeavingSite flag:
$('a, input[type="submit"]').click(function(){ isLeavingSite = false; });
What'll have to do is make use a variable that you set if any link is clicked on the site, then inside the onbeforeunload event check if that variable is set meaning they clicked a link or not set meaning they're closing the tab.
You can also use that variable to simple set the href of the link; that will allow you to then check what link they clicked on inside the onbeforeunload event and allow you to check if they're clicking on a link to go to another page on your site or clicking on an external link to another site.
If your using jQuery try this Confirm before exit

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