为什么 Chrome 会忽略本地 jQuery cookie?

我使用 jQueryCookie 插件(下载小样带注释的源代码)来设置和读取 Cookie。我正在冲洗我的 本地机器本地机器页面。

下面的代码将成功地在 FireFox3、 IE7和 Safari (PC)中设置 cookie。但是 如果浏览器是谷歌浏览器,页面是一个本地文件,它不工作。

$.cookie("nameofcookie", cookievalue, {path: "/", expires: 30});

我所知道的 :

  • 这个插件的 小样可以和 Chrome 一起工作。
  • 如果我把我的代码放在网络服务器上(地址从 http://开始) ,它可以在 Chrome 上工作。

所以这个 cookie 只失败了 谷歌浏览器的本地文件

可能的原因 :

  • 谷歌浏览器不接受来自硬盘上网页的 cookies (路径如 file:///C:/webs.com/foo.html)
  • 插件实现中的某些东西导致 Chrome 拒绝这样的 cookie

有人能证实这一点并找出根本原因吗?

70118 次浏览

Another possible cause is the path: "/", since you're not using a normal web URL, / probably doesn't mean much - try without setting the path at all.

Chrome doesn't support cookies for local files (or, like Peter Lyons mentioned, localhost*) unless you start it with the --enable-file-cookies flag. You can read a discussion about it at http://code.google.com/p/chromium/issues/detail?id=535.

*Chrome does support cookies if you use the local IP address (127.0.0.1) directly. so in the localhost case, that could be an easier workaround.

For local applications use localStorage in Chrome instead: http://people.w3.org/mike/localstorage.html

I had the same issue, please try using the IP address of localhost instead. For e.g "http://127.0.0.1/yoursite/"

please check out Cookies & Google Analytics.

$.cookie("nameofcookie", cookievalue, {path: "/", expires: 30});

change this line to

$.cookie("nameofcookie", cookievalue, {*Path:* "/", expires: 30});

this project working is fine.

i had some problem and solved it this terrible solution. using store and cookie plugin together.

<script src="js/jquery.cookies.2.2.0.js" type="text/javascript"></script>
<script src="js/jquery.Storage.js" type="text/javascript"></script>


var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;


//get cookies
var helpFlag=(is_chrome)?$.Storage.get("helpFlag"):$.cookies.get("helpFlag");


//set cookies
if(is_chrome)$.Storage.set("helpFlag", "1");else $.cookies.set("helpFlag", "1");

I know that this isnt perfect solution but works for me

If you use chrominum this is the command to enable local cookies

chromium-browser --enable-file-cookies

It's the same thing for chrome

Hope this help you !

This did the job for me:

enter image description here

Right click on your Chrome Icon and select Properties, Shortcut tab and add --enable-file-cookies at the last of the target path.

As workaround you can use Tampermonkey with access to local files ( How to include Local htm pages in a Tampermonkey script? ) By that way you will use Tampermonkey's storage, and will be able to set and get your data by functions GM_getValue(data) and GM_setValue(data). I used that for my local HTML page, which i used as customizable alternative to Windows Explorer

But actually localStorage from Yuri's answer works perfect.