views:

176

answers:

4

Hi All

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();
}

Thanks Guys,

Dave

+1  A: 

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.

Developer Art
If Martin's answer is right, this is wrong.
Adriano Varoli Piazza
Relying on JavaScript being not turned off is always a bad solution.
Developer Art
Oh God. How many bearded geeks use noscript? And how many use Links/Elinks/Lynx/some obscure thing with javascript disabled? And how many of them matter to the asker? And, as you said, there's a sort of solution for them or for spiders/bots using server side code, if you care.It's a far cry from 'it's not possible'.
Adriano Varoli Piazza
A: 

Perhaps you could use Ajax to call a PHP file to keep sessions alive on the server side?

John
A: 

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:

Adriano Varoli Piazza
+2  A: 

Your headline and text seem to state two different requirements:

  1. cookie must remain valid until browser is closed, then disappear
  2. cookie must remain valid until browser is closed, then remain valid for another hour, then disappear

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.

Martin
Thanks @Martin, this did the trick. For reference, the second scenario is the one that I wanted.
DaveDev