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; | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This doesn't cover cases where
window.onbeforeunload()
is defined but returnsnull
, meaning it should not prevent navigation. I would change line 8 to: