Javascript 卸载前保存
我有一个带有交互式画布的应用程序,希望在用户退出页面之前在其上保存更改 我的方法 我打电话给你Javascript 卸载前保存,javascript,confirm,Javascript,Confirm,我有一个带有交互式画布的应用程序,希望在用户退出页面之前在其上保存更改 我的方法 我打电话给你 window.onbeforeunload = saveBeforeUnload; 如果用户希望使用当前配置覆盖localStorage项,我需要完成的是/否确认 问题 对于我的代码,确认不会出现。相应地,本地存储是空的。。。 控制台显示“阻塞确认…”进近-I 说明: window.onbeforeload执行处理程序中的任何内容,但它真正关心的是作为确认消息使用的返回语句。当然,我们不能更
window.onbeforeunload = saveBeforeUnload;
如果用户希望使用当前配置覆盖localStorage项,我需要完成的是/否确认
问题
对于我的代码,确认不会出现。相应地,本地存储是空的。。。
控制台显示“阻塞确认…”进近-I
说明:
window.onbeforeload
执行处理程序中的任何内容,但它真正关心的是作为确认消息使用的返回语句。当然,我们不能更改按钮标签。一旦显示onbeforeuload
对话框,它就会阻止所有内容(这就是为什么您的提示会被阻止)。因此,在下面的代码中,我们所做的是使用setTimeout
调度一个save,给出0毫秒,以便将其添加到事件循环中
现在,如果用户决定无论如何关闭选项卡,setTimeout
处理程序永远不会运行。如果他们选择保留,处理程序将运行&更改将被保存
那么,您可以执行以下操作:
function saveChanges () {
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
alert("changes saved successfully !");
window.onbeforeunload = null;
}
function exitConfirmation () {
setTimeout( saveChanges, 0 );
return "There are unsaved changes on this canvas, all your changes will be lost if you exit !";
}
window.onbeforeunload = exitConfirmation(); //Basically set this whenever user makes any changes to the canvas. once the changes are saved window.onbeforeunload is set back to null.
因此,如果用户选择后退,更改将被保存
这是一个可行的解决方案,但在我看来并不是最好的用户体验,因此我建议您在用户进行更改时保持自动保存,并在需要时提供一个按钮重置画布。此外,您不应该每次更改都保存,而是应在特定的时间间隔内自动保存。如果用户试图在该间隔之间关闭,则显示该对话框,说明“您还有待完成的更改”
方法二(你的方式)
但这将是许多唠叨的对话
希望这有帮助。有帮助。令人惊叹的。我已经有一个重置按钮了。因此,我将对该按钮执行删除部分;)非常感谢。也请您解释一下。另请参阅关于第二种方法的更新,但我仍然推荐第一种方法,以获得更好的用户友好体验。在第二种方法中。我是否可以删除“您有未保存的更改”;''line?我认为如果您不返回任何内容,则对话框将不会显示,您必须返回用于显示消息的内容。有关更多详细信息,请使用浏览器历史记录按钮。但当打开另一页时,它就退出了。
function saveChanges () {
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
alert("changes saved successfully !");
window.onbeforeunload = null;
}
function exitConfirmation () {
setTimeout( saveChanges, 0 );
return "There are unsaved changes on this canvas, all your changes will be lost if you exit !";
}
window.onbeforeunload = exitConfirmation(); //Basically set this whenever user makes any changes to the canvas. once the changes are saved window.onbeforeunload is set back to null.
function saveConfirmation () {
if (confirm('Do you want to save the current state to clipboard?')) {
if (canvas.getObjects("rect").length > 0){
localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
} else {
localStorage.setItem("clipboard_unfinishedconfig", "");
return;
}
}
}
function saveBeforeUnload(){
setTimeout( saveConfirmation, 0 );
return "You have unsaved changes";
}
window.onbeforeunload = saveBeforeUnload;