简体   繁体   English

卸载前如何保存网页状态

[英]How to save the state of a web page before unload

I am designing a quiz web application as part of a classroom assignment. 我正在设计一个测验Web应用程序,作为课堂作业的一部分。 The application's goal is to evaluate the javascript skills of a student. 该应用程序的目标是评估学生的JavaScript技能。 When the user closes the browser and revisits the application, the application should check the local storage and display a message asking if the player would like to continue from where he/she left. 当用户关闭浏览器并重新访问该应用程序时,该应用程序应检查本地存储并显示一条消息,询问播放器是否要从他/她离开的地方继续。

So, I want to save the state of an application before the user closes the window or tab. 因此,我想在用户关闭窗口或选项卡之前保存应用程序的状态。

I am using onunload which is not working in chrome. 我正在使用无法在chrome中工作的onunload I tested it in IE and it works fine. 我在IE中测试了它,效果很好。

In IE I have found another problem. 在IE中,我发现了另一个问题。 The onunload function is not able to access the local variables. onunload函数无法访问局部变量。 For example console.log(localVar) is printing undefined as the variable's value. 例如console.log(localVar)打印未定义为变量的值。

At the end I would like to run the application in chrome, mozilla and IE. 最后,我想在chrome,mozilla和IE中运行该应用程序。

I can update the local storage on every user action. 我可以在每次用户操作时更新本地存储。 But this consumes resources on the browser. 但这会消耗浏览器上的资源。 Besides, there is a timer which shows the time left for the quiz to complete. 此外,还有一个计时器,显示完成测验所需的时间。 I am afraid this is a bad approach to update the local storage everytime. 恐怕这是每次更新本地存储的不好方法。 So I thought I will do it in onunload or onbeforeunload functions. 所以我想我会在onunloadonbeforeunload函数中做到这一点。

Below is the code. 下面是代码。

window.onbeforeunload = function() {  // tried both unload and onbeforeunload
        console.log(currentRoundNumber); // prints undefined in IE.
        return false;
    }

You can probably notify the user when trying to leave the page. 尝试离开页面时,您可能会通知用户。 However, updating locationStorage in itself is a better approach though. 但是,更新locationStorage本身是一种更好的方法。

 window.addEventListener("beforeunload", function (e) {
      var confirmationMessage = "\o/";

      (e || window.event).returnValue = confirmationMessage; //IE
      return confirmationMessage;                            //Webkit, Safari, Chrome
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM