Evertjan. wrote:
Michael Winter wrote on 11 dec 2006 in comp.lang.javascript:
[snip]
>... create a cookie (session or future-dated, it doesn't matter)
then reassign that cookie with a date in the past. If the cookie
can be read after the first assignment but not after the second,
then it is reasonable to conclude that the user agent will not send
expired cookies. This approach is easily included while testing the
property.
[snip]
Do we put your solution in the FAQ, and then how?
I don't know. It looks a little messy as a single function, but can look
rather intimidating as a collection.
Below is collection of cookie-related methods that I wrote a while ago.
The makeAge method isn't used by the isSupported method.
var Session = function () {
var supported = false;
return {
get: function (name) {
var match = new RegExp('(^|;)\\s*' + name
+ '\\s*=\\s*([^\\s;]+)').exec(document.cookie);
return match ? match[2] : null;
},
set: function (name, value, maxAge, path, domain) {
var cookie = name + '=' + value;
if (maxAge !== 0) {
var expires = new Date();
expires.setUTCSeconds(maxAge
+ expires.getUTCSeconds());
cookie += ';expires=' + expires.toGMTString();
}
if (path) cookie += ';path=' + path;
if (domain) cookie += ';domain=' + domain;
document.cookie = cookie;
},
remove: function (name, path, domain) {
this.set(name, 'deleted', -1, path, domain);
},
isSupported: function () {
if (typeof document.cookie == 'string') {
var name = 'test',
value = 'foobar';
while (this.get(name) != null) name += '-' + name;
this.set(name, value, 30);
if ((this.get(name) == value)
&& (this.get('expires') == null)) {
this.remove(name);
supported = (this.get(name) == null);
}
}
this.isSupported = function () {return supported;};
return supported;
},
makeAge: function (days, hours, minutes, seconds) {
return ((days * 24 + (+hours || 0)) * 60
+ (+minutes || 0)) * 60 + (+seconds || 0);
}
};
}();
The age value in the test is arbitrary, really. A value of 2 should
suffice, but a larger number makes no difference. An indication of
success requires the data to be deleted, anyway.
>>I propose window.navigator.cookieEnabled is worth of inserting in
the FAQ.
Opposed. It is no more reliable
That is no reason not to put it in the FAQ.
It's certainly one reason.
It is an easy solution, much shorter than a whole function:
Is the property guaranteed? Does the property represent client-side
state management in general, or specifically that the document.cookie
property is usable? The former doesn't need to imply the latter; the
former is potentially useful information on its own. Given the nature of
the property, those are not easy questions to answer accurately.
[snip]
>(and possibly less so).
Could be, but if so, we should determine that first.
Richard already presented one reason why it definitely is, though I was
leaning more towards the existence of the property itself. Proving that
to any degree of certainty is impractical, as you should well know.
Mike