I want to execute js script before a connection is closed, for example when I closed the web-page or refresh it. 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)
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:
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();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.