// 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); } } };