HTML/Javascript: how to stop navigating off a page
ugh. more javascript. I hate it. I wouldn't mind it if all the browsers were the same.
I need to prevent users from exiting a page if their data is unsaved. I've got a flag being set if they change information in a form, then I have this:
var hasChanged = 0;
function setChanged() {
hasChanged = 1;
}
function clearChanged() {
hasChanged = 0;
}
window.onunload=hasItChanged();
function hasItChanged() {
if (hasChanged == 1) {
history.go(0);
return false;
}
return true;
}
or something close to this...
This works for Mozilla, but not IE. (history.go(0) doesn't do anything in IE 5.5 and the next page loads) any ideas?
AI Summary
7 Comments
I give up. you can't stop "unload" in IE (it seems you can in Mozilla).
so I guess I'm gonna have to add onClick handlers to all the links and buttons that submit, and have them check the flag.
just found out another annoying thing, the request is being sent to the server, even when it works in Mozilla. what I'd really like to be able to do is catch any attempt to move off the page (but only if a flag is set), before a request is being sent to the server, then decide whether to continue or not based on a confirmation dialog sent to the user.
history.back() works for IE, I believe.
but the problem here is that if the user is leaving the page by going to any other page, forward in the site, some other site altogether, or whatever, window.unload() will run, and it will send them back a page. how are you preventing that?
history.back() is the equivalent of history.go(-1)
I'm doing history.go(0) which keeps you where you are. works in Mozilla, not in IE.
you're only prevented if hasChanged == 1, and also, I have a confirmation dialog, that I removed for clarity, so you can leave if you really want to.
oh yeah.. i fooled myself with the 0/-1 thing.
do you really have to prevent them from hitt Back? It would be a lot easier if you just checked hasDirty() when clicking on any submit buttons or UI links.
back isn't important, I need a way of preventing them from leaving the page when they:
1) click any link in the page
2) click any button in the page (except the save changes button, which will clear the dirty flag)
How would I do this? I can't add onClick()'s to every link in the page, because some of them are from an included page that has navigation links, and is used on pages where there is no dirty flag.
Say you're on page 2, and you click a link, and the hasDirty flag is set. if I used history.back(), I'd be sent to page 1. I want to stay on page 2.
by