卸载前保存

gco*_*gco 4 javascript confirm

我有一个带有交互式画布的应用程序,想要在用户退出页面之前在其上保存更改。

我的方法

      function saveBeforeUnload(){ 
         if (confirm('Do you want to save the current state to clipboard?')) {
        /*yes*/  if (canvas.getObjects("rect").length > 0){
                    localStorage.setItem("clipboard_unfinishedconfig", JSON.stringify(canvas.toJSON(customProperties)));
                    return;
        /*no:*/  } else { 
                   localStorage.setItem("clipboard_unfinishedconfig", "");
                return;
            }
      }
Run Code Online (Sandbox Code Playgroud)

我叫它

    window.onbeforeunload = saveBeforeUnload;
Run Code Online (Sandbox Code Playgroud)

如果用户想使用当前配置对localStorage项进行操作,我需要完成的是是/否确认。

问题

使用我的代码,确认不会出现。因此,localStorage为空...控制台显示“阻止确认...”

Mud*_*Ali 5

方法-我

说明:

window.onbeforeload执行处理程序中的任何内容,但它实际上关心的是将用作确认消息的return语句。当然,我们不能更改按钮标签。一旦onbeforeunload对话框显示它阻止一切(这就是为什么你的提示被阻止)。因此,在下面的代码中,我们正在做的是使用setTimeout0毫秒来安排使用a 进行保存,以便将其添加到事件循环中。

现在,如果用户决定以任何方式关闭选项卡,则该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.
Run Code Online (Sandbox Code Playgroud)

因此,如果用户选择留下,则更改将被保存,

这是一个可行的解决方案,但我认为并不是最佳的用户体验,因此我建议您在用户进行操作时自动保存更改,并在需要时提供一个按钮以重置画布。同样,您不应该保存每个更改,而应在特定时间间隔内保留自动保存。如果用户尝试在该间隔之间关闭,则显示此对话框,提示“您还有待处理的更改”。

方法-II(您的方式)

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;
Run Code Online (Sandbox Code Playgroud)

但这将是许多烦人的对话。

希望这可以帮助。