简体   繁体   English

在 OnDisconnected 方法之前执行脚本

[英]execute script before OnDisconnected method

I want to execute js script before a connection is closed, for example when I closed the web-page or refresh it.我想在关闭连接之前执行 js 脚本,例如当我关闭网页或刷新它时。 I have OnDisconnected method on the server-side, and it works well, but I can`t use local storage, so and need to execute a script on the client-side (In my case save the date when the user is disconnected, to local storage)我在服务器端有 OnDisconnected 方法,它运行良好,但我不能使用本地存储,所以需要在客户端执行一个脚本(在我的情况下,保存用户断开连接的日期,以本地存储)

Something like this:像这样的东西:

connection.disconnected(function () {
    var date = new Date();
    localStorage.setItem("disconnDate", date);
});

UPDATE.更新。 Solved this problem this way:以这种方式解决了这个问题:

window.onbeforeunload = function (e) {
    var date = new Date();
    localStorage.setItem("disconnDate", date);
};

You can use onclose method of Client-Side connection:您可以使用客户端连接的onclose方法:

connection.onclose(() => {
    var date = new Date();
    localStorage.setItem("disconnDate", date);
});


UPDATE更新

If you want to work this code on leaving page.如果您想在离开页面时使用此代码。 You can add such event listener您可以添加此类事件侦听器

window.addEventListener('beforeunload', (event) => {
   connection.stop();
});

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

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