Skip to content

Instantly share code, notes, and snippets.

@pedroteixeira
Last active December 27, 2015 17:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroteixeira/7363217 to your computer and use it in GitHub Desktop.
Save pedroteixeira/7363217 to your computer and use it in GitHub Desktop.
onbeforeunload support for js navigation (via hashchange, such as backbone.history, etc)
var cancelNavigate;
$(window).on("hashchange", function(ev) {
if(cancelNavigate) {
cancelNavigate = false;
return false;
}
if(window.onbeforeunload) {
var ok = confirm(window.onbeforeunload());
if(ok) {
window.onbeforeunload = null;
return;
} else {
cancelNavigate = true;
window.location.href = ev.originalEvent.oldURL;
return false;
}
}
});
@pedroteixeira
Copy link
Author

It does not work on IE, because it does not have the oldURL property.. for these case, you have to manually track the previous href.

@sekoyo
Copy link

sekoyo commented Jun 10, 2015

Thanks for this

@nfvs
Copy link

nfvs commented Sep 25, 2015

This doesn't cover cases where window.onbeforeunload() is defined but returns null, meaning it should not prevent navigation. I would change line 8 to:

var msg = window.onbeforeunload();
if (!msg) return;
var ok = confirm(msg);
if (ok) {

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment