Skip to content

Instantly share code, notes, and snippets.

@codethug
Last active December 11, 2015 20:48
Show Gist options
  • Save codethug/4657291 to your computer and use it in GitHub Desktop.
Save codethug/4657291 to your computer and use it in GitHub Desktop.
A custom binding for KnockoutJS allowing you hook into the onbeforeunload event on the window. This will allow you to display a message to the user when navigating away from or closing the page, reminding the user to save their work, etc.
// Author: Tim Larson @codethug
ko.bindingHandlers.beforeUnloadText = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel) {
if (window.onbeforeunload == null) {
window.onbeforeunload = function(){
var value = valueAccessor();
var promptText = ko.utils.unwrapObservable(value);
if (typeof promptText == "undefined" || promptText == null) {
// Return nothing. This will cause the prompt not to appear
} else {
if (promptText != null && typeof promptText != "string") {
var err = "Error: beforeUnloadText binding must be " +
"against a string or string observable. " +
"Binding was done against a " + typeof promptText;
console.log(err);
console.log(promptText);
// By returning the error string, it will display in the
// onbeforeunload dialog box to the user. We could throw an
// exception here, but the page would unload and the
// exception would be lost.
return err;
}
return promptText;
}
};
} else {
var err = "onbeforeupload has already been set";
throw new Error(err);
}
}
};
@Mariatta
Copy link

Hi do you think you can provide an example on how to use this?

Thank you.

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