Expire sessions after n hours in Webchats with persistent history

If the Webchat conversation should be persistent across page navigations or page reloads, one can implement the Persistent History decribed on Github: https://github.com/Cognigy/WebchatWidget/blob/master/docs/persistent-history.md. However, in this scenario, the session never ends for the Webchat user as the messages stay in the chat window.

If the session should expire after a configured time, one can use the following extension of the Persistent History Code:

Edit webchat-persistent-history-session-timeout

// Initialize a sessionId, undefined by default.
let sessionId;
let sessionStartDate;

// in case LocalStorage is supported...
if (window.localStorage) {
sessionStartDate = new Date(
window.localStorage.getItem("SESSIONSTARTDATE")
);

let currentDate = new Date();

// calculate session time in hours
let hours = Math.abs(sessionStartDate - currentDate) / 36e5;

// check if session is outdated
// Expire after 48 hours
if (hours >= 48) {
window.localStorage.removeItem("SESSIONID");
window.localStorage.removeItem("SESSIONSTARTDATE");
} else {

// try to load a previously stored sessionId from the LocalStorage
sessionId = window.localStorage.getItem("SESSIONID");
}

// in case there was no previously stored sessionId,
// generate one and store it into LocalStorage
if (!sessionId) {
sessionId = "session-" + Date.now() * Math.random();
sessionStartDate = new Date();
localStorage.setItem("SESSIONSTARTDATE", sessionStartDate);
localStorage.setItem("SESSIONID", sessionId);
}
}

initWebchat("...", { sessionId: sessionId }).then(function (webchat) {
webchat.open();
});

In the example above, the session will expire after 48 hours.


Comments

0 comments

Article is closed for comments.

Was this article helpful?
0 out of 0 found this helpful