Last active
December 27, 2015 17:39
-
-
Save pedroteixeira/7363217 to your computer and use it in GitHub Desktop.
onbeforeunload support for js navigation (via hashchange, such as backbone.history, etc)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}); |
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
Thanks for this