Skip to content

Instantly share code, notes, and snippets.

@pedroteixeira
Last active December 27, 2015 17:39
Show Gist options
  • Select an option

  • Save pedroteixeira/7363217 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown
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.

@dominictobias
Copy link
Copy Markdown

Thanks for this

@nfvs
Copy link
Copy Markdown

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