Reputation: 42205
I have a page that displays data which is read from a cookie. The cookie expires after an hour. Frequently, a user will navigate to the page and keep it open. When they come back to it later, the cookie has expired and the data on the page is no longer relevant.
Can anyone suggest how I can set the cookie's expiration time to last the length of the session?
For reference, this is the code I'm using to set the cookie (which I lifted from another project we have, and which may in turn have been lifted from this site! :-)
function setCookie(value)
{
var today = new Date();
today.setTime(today.getTime());
var expires = 30 * 1000 * 60;
var c_name = 'CompareFundIds';
var exdate = new Date(today.getTime() + (expires));
document.cookie = c_name + "=" + value + ";expires=" + exdate.toGMTString();
}
Upvotes: 2
Views: 1693
Reputation: 38309
Your headline and text seem to state two different requirements:
1) will work if you set no "expires" value at all for the cookie:
// Set cookie until browser is closed
document.cookie = c_name + "=" + value;
2) will work if you let your setCookie function run repeatedly as long as the page is open, say every minute:
// Set cookie every minute
var value = ...;
window.setInterval(function () {
setCookie(value);
}, 60 * 1000);
When the browser is closed, the cookie will never be older than 1 minute and will thus be valid for another hour.
Upvotes: 2
Reputation: 7429
Is this not possible to do using the onUnload / onClose javascript events? Ideally, you could set some behavior on page load, then another on page unload. Granted, onClose is not supported by all browsers, but I see that jQuery does support an onunload method.
References:
Upvotes: 0
Reputation: 2264
Perhaps you could use Ajax to call a PHP file to keep sessions alive on the server side?
Upvotes: 0
Reputation:
Can anyone suggest how I can set the cookie's expiration time to last the length of the session?
This is not possible, as far as I know it.
What you can do is to change your server logic. Mirror the values in both session and cookies. Read first from the session, if it's not there, then fall back for cookies. That should do the trick.
Upvotes: 1