Save before unload - javascript

I'm having an application with an interactive canvas and want to save changes on it, before the user exits the page.
My approach
function saveBeforeUnload(){
if (confirm('Do you want to save the current state to clipboard?')) {
/*yes*/ if (canvas.getObjects("rect").length > 0){
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
return;
/*no:*/ } else {
localStorage.setItem("clipboard_unfinishedconfig", "");
return;
}
}
I call it by
window.onbeforeunload = saveBeforeUnload;
What I need to accomplish is a yes/no confirmation, if the user wants to ovverride the localStorage Item with the current configuration.
Problem
With my code, the confirm does not appear. Accordingly the localStorage is empty...
console says "Blocked confirm..."

Approach - I
Explanation:
window.onbeforeload executes whatever is in the handler but it really cares about the return statement which shall be used as confirmation message. And Ofcourse we can't change the button labels. Once the onbeforeunload dialog is shown it blocks everything(that's why your prompt is blocked). So in the following code what we are doing is that we are scheduling a save using a setTimeout by giving 0 milliseconds, so that it is added to the event loop.
Now if the user decides to close the tab anyway that setTimeout handler never runs. If they choose to stay, the handler runs & the changes are saved.
Well, you can do the following:
function saveChanges () {
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
alert("changes saved successfully !");
window.onbeforeunload = null;
}
function exitConfirmation () {
setTimeout( saveChanges, 0 );
return "There are unsaved changes on this canvas, all your changes will be lost if you exit !";
}
window.onbeforeunload = exitConfirmation(); //Basically set this whenever user makes any changes to the canvas. once the changes are saved window.onbeforeunload is set back to null.
So, If the user chooses to stay back, the changes will be saved,
This is a working solution, but not the best user experience in my opinion, so what I suggest is that you keep auto saving the changes as the user makes & give a button to reset the canvas if required. Also you should not save on every single change, but instead keep auto saving in a specific interval of time. If the user tries to close between that interval then show this dialog saying "you have pending changes left".
Approach - II ( Your way )
function saveConfirmation () {
if (confirm('Do you want to save the current state to clipboard?')) {
if (canvas.getObjects("rect").length > 0){
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
} else {
localStorage.setItem("clipboard_unfinishedconfig", "");
return;
}
}
}
function saveBeforeUnload(){
setTimeout( saveConfirmation, 0 );
return "You have unsaved changes";
}
window.onbeforeunload = saveBeforeUnload;
But this will be to many nagging dialogs.
Hope this helps.

Related

How can I warn user on back button click?

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.

Javascript/jQuery Popup Loop and Add

Firstly, I am quite new to programming, so please be gentle. Stack Overflow has been a wonderful resource for me, so thankyou to all of you contributors.
This one I cannot crack though, and it's a difficult search item, as you can probably tell by the cryptic title...
Anyway, I have a jQuery popup function which gets called from a events.register control. Essentially whenever a user clicks in the map it sends a request to a web service, gets the data back, populates a form which the user can then interact with and save data back to SQL.
It works really well I am happy with its progress.
One of the functions is to change the value in a table, I want the user to get a prompt to ensure they don't accidentally save something they don't intend. It works perfectly the first time after a refresh, but then each time after that it adds one confirm, then again, until eventually after the fifth time there are 5 confirms that appear one after the other. Once the user clicks through them the code runs fine and I get expected results.
I only call the confirm once (I think?) but, yeah, I am lost, here is my function, sorry if it is hard to read or poorly formatted:
function popup() {
j = jQuery.noConflict();
j(document).ready(function() {
//open popup
j("#detailsform").height(250);
j("#detailsform").fadeIn(1000);
positionPopup();
document.getElementById("condition").value = getCondition;
j("#selCatHead").hide();
j("#cats").hide();
//dispose tree
j("#dispose").click(function() {
if (confirm("Are you sure?")) {
disposetree();
}
else { return false; };
});
//save defect
j("#savedef").click(function() {
saveDef();
});
//fade in defects
j("#adddefect").click(function() {
j("#detailsform").height(400);
j("#selCatHead").fadeIn(1000);
j("#cats").fadeIn(1000);
});
//fade out popup
j("#close").click(function() {
j("#detailsform").fadeOut(500);
});
}); // close document ready function
//position the popup at the center of the page
function positionPopup() {
if (!j("#detailsform").is(':visible')) {
return;
}
j("#detailsform").css({
left: (j(window).width() - j('#detailsform').width()) / 2,
top: (j(window).width() - j('#detailsform').width()) / 7,
position: 'absolute'
});
} // close positionPopup function
//maintain the popup at center of the page when browser resized
j(window).bind('resize', positionPopup);
}; // close popup function
EDIT: Thanks to #jfriend00, removed function from popup call and turned off handler each time, eg:
function popup() {
j = jQuery.noConflict();
j(document).ready(function() {
//open popup
j("#detailsform").height(250);
j("#detailsform").fadeIn(1000);
//dispose
j("#dispose").off();
j("#dispose").click(function() {
disposeClickHandle();
});
//save
j("#savedef").off();
j("#savedef").click(function() {
saveDef();
});
});
and then:
function disposeClickHandle() {
if (confirm("Are you sure?")) {
disposetree();
}
else { return false; };
};
You should only install a click handler ONCE. If you install it multiple times, it will trigger multiple times.
So, everytime you call your popup() function it installs yet another click handler. And, then when you click, the click handler will trigger multiple times. You should either move your click handler installation outside the function that you call multiple times and put it in an initialization function that is only called once at the beginning OR you can remove the click handlers after your operation so when you install it again, it will only be installed one time.

Call a function on page refresh using Javascript

function warnuser()
{
return "Don't refresh the page.";
}
window.onbeforeunload = warnuser;
If the user refreshes the page and the user clicks 'leave this page' on confirmation box, i want to call a javascript function , otherwise not!
I am confused about how to do that.
Thank you
You need to intercept the F5 key press and setup the onbeforeunload handler only in that case:
document.addEventListener('keydown', function(e) {
if(e.which == 116) {
window.onbeforeunload = function() {
window.onbeforeunload = null;
return "Do you really want to refresh the page?";
}
}
}, false);
Demo: http://jsfiddle.net/ejDrq/
Note that this does not work if the user clicks the Refresh button. It is impossible to intercept this.
If you have control of the server side which is hosting the page then you can handle this logically with a semaphore (wiki:semaphore). Basically it is a spinning lock which would be implemented in their server side session. Resetting the page state if they have entered and not exited in a safe manner. Naturally, as with all spinning locks, there would have to be a safe state to clear the lock out.

How to capture when a user is leaving ASP.Net page unexpectedly

I need to prompt a user when they are leaving my ASP.Net page unexpectedly with a message to ask if they are sure they want to leave. A post back or when the save button is clicked should not fire the warning. There are a bunch of articles covering this but I am brand new to this and appear to have got my wires crossed.
The recommended way appears to be to use the window.onbeforeunload event but behaves unexpectedly for me. This is fired when the page loads as opposed to when the page unloads.
<script language="JavaScript" type="text/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>
If I use the JQuery implementation it fires when the page unloads but the problem is it fires before the code behind is executed. So I cannot set a variable on the client saying don’t fire the event this time as it is a post back or a Save.
$(window).bind('beforeunload', function () {
return 'Are you sure you want to leave?';
});
Can anyone point me in the correct direction as I know I am making basic mistakes/miss-understanding?
Edit:
So I am nearly there:
var prompt = true;
$('a').live('click', function () {
//if click does not require a prompt set to false
prompt = false;
});
$(window).bind("beforeunload", function () {
if (prompt) {
//reset our prompt variable
prompt = false;
//prompt
return true;
}
})
Except the problem is in the above code I need to be able to differentiate between the clicks but I haven't been able to figure that out yet i.e. I am missing a condition here "//if click does not require a prompt set to false".
Any ideas?
Thanks,
Michael
You can try using this:
$(window).unload(function(){
alert('Message');
});
In case people are interested this is the roundabout solution to my problem. How to tell if a page unload in ASP is a PostBack

How to determine when a user is leaving a webpage (excluding certain links)

The situation: I have a Grails webpage with two tables. One table displays a persons information (including certain flags), and the second table has a list of flags with an "add button" that allows the user to add a given flag to themselves.
Now, there is a save button that, when clicked, pushes the current "state" of the users flags to our database. So I want to be able to display a prompt if there is unsaved information being displayed when a user tries to navigate to another part of the site. This is easy enough by using an existing isDirty boolean that each flag stores. I can just loop through the persons active flags and check if it is dirty or not. If the person contains at least 1 dirty flag, I need to display a prompt if they try to leave, because that data won't be saved unless they explicitly hit the button.
The problem: There are many ways to navigate away from this page. I am using
<body onbeforeunload="checkForDirtyFlags();">, where checkForDirtyFlags() is a basic js function to check for any dirty flags. But here's the thing - when a user adds or removes a flag, that causes a page reload because the way the page is setup is to redirect to a url like this:
"http://my.url/addFlag/123456"
The controller then knows to add the flag with id 123456 to the current person. This does NOT change where the person is in the website however, because the same page is still rendered (it just contains updated tables). So basically, when I see a URL with addFlag or removeFlag, I do not want to prompt the user if they are sure they want to navigate away from the page, because in the eyes of the user they are not leaving the page.
The question: Is there any way to determine what the target is during an onbeforeunload? So that I can have something like this in my javascript:
function checkForDirtyFlag() {
if( justAdding ) { //We are just adding a flag. No prompt necessary
//Don't do anything
}
else if( justRemoving ) { //We are just removing a flag. No prompt necessary
//Don't do anything
}
else { // In this case, we want to prompt them to save before leaving
alert('You have unsaved data on the page. Leaving now will lose that data. Are you sure you want to leave?');
}
}
If any of this isn't clear, please let me know and I'll try and clear it up.
Thanks!
I don't think you can get the target location in unload event. What I'd do is bind the save/submit button to a function that disables the unload event if the button is pressed, therefore disabling the prompt. If the user tries to leave by pressing back etc, the unload event would fire.
Why don't you push the changes immediately to the database, without them having to press the Save Button, or store them in a temporary database so that they do not lose their unsaved changes when the navigate to a different part of the site.
I'm not quite sure if I get you right - but you actually wrote the solution already down there. Why don't you just return a string-message from within an onbeforeunload when necessary ?
For instance:
window.onbeforeunload = function() {
if( justAdding ) { //We are just adding a flag. No prompt necessary
//Don't do anything
}
else if( justRemoving ) { //We are just removing a flag. No prompt necessary
//Don't do anything
}
else { // In this case, we want to prompt them to save before leaving
return 'You have unsaved data on the page. Leaving now will lose that data. Are you sure you want to leave?';
}
};
If you return a string value from that event, the browser will take care of a modal dialog window which shows up. Otherwise nothing happens.

Categories

Resources