5.9 Detecting Cookie Availability
NN 2, IE 3
5.9.1 Problem
You
want your
scripts to know whether the user's browser has
cookies enabled.
5.9.2 Solution
Internet Explorer 4 or later and Netscape 6 or later feature the
navigator.cookieEnabled property, which you can test at any
place within a script:
if (navigator.cookieEnabled) {
// invoke cookie statements here
}
For earlier versions of these browsers, you can test whether cookies
are enabled by first checking for the presence of a value stored in
the cookie. If no data is there, you can test write a cookie to see
if it "sticks":
var cookieEnabled = false;
if (typeof document.cookie = = "string") {
if (document.cookie.length = = 0) {
document.cookie = "test";
cookieEnabled = (document.cookie = = "test");
document.cookie = "";
} else {
cookieEnabled = true;
}
}
5.9.3 Discussion
The longer solution also works with browsers that have the
navigator.cookieEnabled property, so you can use
one solution for all scriptable browsers. The first
if construction
verifies that the document.cookie property returns
a string value, which it does even when cookies are disabled by the
user. If the string has any content, you know that cookies are
enabled and that the cookie is in use for the domain that served up
the current page. But if the string is empty, you can assign a simple
value to it and see if it "sticks."
If the value can be read back, cookies are enabled, and you empty the
cookie so as not to disturb it for regular usage.
5.9.4 See Also
Recipe 1.9 for using client-side cookies; Recipe 10.4 for using
cookies to pass data from document to document.
|