Pacerier
Pacerier

Reputation: 89653

Chrome: Is the order of document.cookie guaranteed?

document.cookie='foobar'

.followed by:

console.log(document.cookie.indexOf('foobar'))

.always gives me 0 when tested on Chromes.

Is the order guaranteed (by anything) for Chrome?

(Also might be interested in Ecmascript /Firefox /etc.)

Upvotes: 0

Views: 965

Answers (2)

Ivar
Ivar

Reputation: 6848

No, the order is not guaranteed.

The document.cookie is an accessor property with native setter and getter functions. If you set a value, a single cookie will be added/updated. If you get the value, a semicolon-delimited list of all the cookies will be returned.

The order in which the list will be returned (as far as I could find) is undefined behavior. The definition of document.cookie from the "Document Object Model (DOM) Level 2 HTML Specification" only states that:

When this attribute is read, all cookies are returned as a single string, with each cookie's name-value pair concatenated into a list of name-value pairs, each list item being separated by a ';' (semicolon).

In general (tested on Chrome/Firefox/Edge) it seems that cookies that are set first using the document.cookie, are returned first. So in your case, if you have set another cookie before you set "foobar", then "foobar" wont be at string index 0.

document.cookie='anothercookie=anothercookie';
document.cookie='foobar=foobar';

console.log('cookie', document.cookie); // cookie anothercookie=anothercookie; foobar=foobar
console.log('index', document.cookie.indexOf('foobar')); // index 29

Interestingly, it seems that cookies that are set using the set-cookie header are placed after the cookies that are set using the document.cookie, eventhough they are set first. A fiddle can be found here.

Upvotes: 1

zmag
zmag

Reputation: 8251

I think you may consider document.cookie as some kind of array. But document.cookie is just a string.

'foobar'.indexOf('foobar') returns 0 because foobar has been found at index 0.

Upvotes: 0

Related Questions