How to stop unloading the page? - javascript

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.

Related

Handle browser back button with angular in controller

I want to handle browser back button with angular, i have tried many solution but i cant find one which is fulfill my requirement,
here is my tried code.
$scope.$on('$locationChangeStart', function(event, newUrl, oldUrl) {
if(!allowed /* inject your logic here */) {
event.preventDefault();
}
});
it is working fine when i go to particular page from my app, but if go from e.g www.google.com direct to that particular page by pasting link then it just get back to Google.
what is actually i want handle both scenario of back button.
is it possible?
I will really appreciate your response,
these are the links I have tried but problem remain same.
How to detect browser back button click event using angular?
How to handle browser back button event in a particular controller?
Have you tried using 'window.onbeforeunload'?
For example:
window.onbeforeunload = function()
{
//Do whatever here for example prompt user
return "Are you sure you want to go back?";
};

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.

Detect/Warn when back button is pressed

Is there a way detect/catch the browser back button being pressed and in doing so ask them if they are sure about going back?
Building an application and it will soon be converted to an ajax based application and per requirements it's supposed to reset the application if a user goes 'back'...
I mainly want this to catch the accidental back button presses as I personally feel that if someone can't follow the directions that are given to them at the beginning of the application.... I'm not worried about their extra work.
If there isn't a way to do this is would the best solution be to launch the application in a new window/tab so that there is no history for it to go back to?
you can use onbeforeunload to detect back button or accidental page navigations:
window.addEventListener("beforeunload", function() {
var ans = confirm("Are you sure?");
if (ans) {
//TODO: add your code here
}
}, false);
to replace the current page in browser history you can use window.location.replace():
window.location.replace("yourNewURL");
You can also set the onbeforeunload function like this:
window.onbeforeunload = function() {
return "Are you sure you wish to leave?";
};

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

Save record on page leave

I am saving records on save button click, if user don't click save button and navigate to another page while clicking on some link even then i want to call the save method.
How can I achieve this functionality?
please provide some sample code ...
thanks in advance for your help
You can make ajax request on
window.onbeforeunload = function(){
////make ajax request
}
Or can prevent the user by giving confirm box
function showalert() {
if (!confirm('Are you sure you want to exit without saving changes?')) {
////make ajax request
}
else {return true;}
}
window.onbeforeunload = function(){ showalert }
For example check this out when I leave this page while answering SO prevent me
Use an ajax post, triggered by window.OnBeforeUnload() to let yourself know that the user has left the page, and pass any information you need.
Well since you want to call the save method even if the user navigates to another page or link
what u need to do is set a hidden field for eg. suppose hdnSave and set its value to say 0
Now when the user navigates or clicks on any another link first check if this hidden field value(hdnSave) is set to 1 or not.If not then Call Save Method.So this hidden Field can be used as an indicator of whether Save Method has been called or not.
Similarly you can use a session(in c# code) for the same purpose as well.

Categories