简体   繁体   中英

document.cookie not storing cookie?

Does document.cookie only work on a server? Alert doesn't seem to be outputting my cookie.

document.cookie = "d=e";
alert(document.cookie);

Some browsers won't honor cookies when set by a document with the file protocol.

Chrome intentionally disables cookies on file://, for a variety of reasons. When we wrote our cookie support, the correct behavior was unclear when dealing with things like file shares. We found cookies on file:// to be fairly uncommon, and it has a few negative security implications.

You can, however, enable them with the command line flag --enable-file-cookies.

Cookies are strictly a HTTP mechanism as per RFC 2109. There should be no reasonable expectation for them to work for protocols other than HTTP, much less file:///, and it is not clear what their behavior should be, and what rules of security compartmentalization should apply.

Source .

Cookies are associated with a particular domain. If you just open your HTML document as a file, then how is the browser to know what domain to associate a cookie with, or what cookies it should allow that file to access?

So yes, for all practical purposes, your browser will only allow cookies to be stored and retrieved if your HTML document is served by a server/accessed via an HTTP URL that allows it to determine some sort of domain to associate the cookie(s) with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM