无法在 Javascript 中设置 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8105135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:45:09  来源:igfitidea点击:

Cannot set cookies in Javascript

javascriptgoogle-chromecookies

提问by KMC

I have a very simple line of code that set and read a cookie. I kept getting empty value for my cookie and have no understanding why. I have cookie enabled and know that cookies work on the browser.

我有一行非常简单的代码来设置和读取 cookie。我一直为我的 cookie 获取空值,但不明白为什么。我启用了 cookie,并且知道 cookie 可以在浏览器上运行。

<HTML>
    <HEAD>
        <TITLE>Hello World</TITLE>
    </HEAD>
    <BODY>
        <SCRIPT type="text/javascript">
            document.cookie = "ding=dong";
        </SCRIPT>
        <script type="text/javascript">
            alert(document.cookie);
        </script>
    </BODY>
</HTML>

回答by Dmitry Vyal

Recently I stumbled upon a similar issue. My script couldn't store a cookie in Chromium, although it worked well on all other major browsers. After some googling it turned out that Chrome ignores cookies from local pages. After I uploaded the page to remote server code magically started to work.

最近我偶然发现了一个类似的问题。我的脚本无法在 Chromium 中存储 cookie,尽管它在所有其他主要浏览器上运行良好。经过一番谷歌搜索,结果发现 Chrome 忽略了来自本地页面的 cookie。在我将页面上传到远程服务器后,代码神奇地开始工作。

回答by user2257736

Chrome denies file cookies. To make your program work, you going to have to try it in a different browser or upload it to a remote server. Plus, the code for your setcookie and getcookie is essentially wrong. Try using this to set your cookie:

Chrome 拒绝文件 cookie。为了使您的程序工作,您必须在不同的浏览器中尝试它或将其上传到远程服务器。另外,您的 setcookie 和 getcookie 的代码本质上是错误的。尝试使用它来设置您的 cookie:

function setCookie(name,value,expires){
   document.cookie = name + "=" + value + ((expires==null) ? "" : ";expires=" + expires.toGMTString())
}

example of usage:

用法示例:

var expirydate=new Date();
expirydate.setTime( expirydate.getTime()+(100*60*60*24*100) )
setCookie('cookiename','cookiedata',expirydate)
// expirydate being a variable with the expiry date in it
// the one i have set for your convenience expires in 10 days

and this to get your cookie:

这是为了获取您的 cookie:

function getCookie(name) {
   var cookieName = name + "="
   var docCookie = document.cookie
   var cookieStart
   var end

   if (docCookie.length>0) {
      cookieStart = docCookie.indexOf(cookieName)
      if (cookieStart != -1) {
         cookieStart = cookieStart + cookieName.length
         end = docCookie.indexOf(";",cookieStart)
         if (end == -1) {
            end = docCookie.length
         }
         return unescape(docCookie.substring(cookieStart,end))
      }
   }
   return false
}

example of usage:

用法示例:

getCookie('cookiename');

Hope this helps.

希望这可以帮助。

Cheers, CoolSmoothie

干杯,酷冰沙

回答by John Castell

I tried to save an cookie on Chrome and had the same error, that it would save. Although it did work in Firefox, so I asked an collegue and he suggested that I take away path and domain (I had name of cookie, value, expire, path amd domain) and all of a sudden it worked. So just to get the cookie to actually save in Chrome, you just need name, value and expire.

我试图在 Chrome 上保存一个 cookie,但出现了同样的错误,它会保存。虽然它在 Firefox 中确实有效,所以我问了一位同事,他建议我去掉路径和域(我有 cookie 的名称、值、过期、路径和域),突然之间它起作用了。因此,为了让 cookie 实际保存在 Chrome 中,您只需要名称、值和过期时间。

Hope it helps.

希望能帮助到你。

Example:

例子:

function createCookie(name,value,days) {
     if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = name+"="+value+expires+";";
}

回答by maudulus

With chrome, you cannot create cookies on a local website, so you need to trick your browser into thinking this site is not local by doing the following:

使用 chrome,您无法在本地网站上创建 cookie,因此您需要通过执行以下操作来欺骗您的浏览器认为该站点不是本地站点:

1) Place the root directory of the web site into C:\inetpub\wwwroot, (so it looks like C:\inetpub\wwwroot\yourProjectFolder)

1) 把网站的根目录放到C:\inetpub\wwwroot, (看起来像C:\inetpub\wwwroot\yourProjectFolder)

2) Get your computer nameby right clicking Computer, clicking properties, and looking for Computer Name

2)computer name通过右键单击Computer,单击属性并查找来获取Computer Name

3) Access your site in the browser by visiting http://my-computer-name/yourProjectFolder/index.html, at which point creating cookiesshould work.

3) 通过访问在浏览器中访问您的站点http://my-computer-name/yourProjectFolder/index.html,此时创建 cookie应该可以工作。

(notice that I use dashes in the computer name, NOT underscores)

(请注意,我在计算机名称中使用破折号,而不是下划线

回答by Anne Lingesh

Chrome doesn't store cookies from the pages which are loaded from local file system. ex: file:///C:/User

Chrome 不会存储从本地文件系统加载的页面中的 cookie。例如:file:///C:/User

回答by LaustN

I get the same weird behavior when opening a page in Chrome from localhost

在 Chrome 中打开页面时,我得到了同样奇怪的行为 localhost

When I map the same page in my hosts file and open the same page through the mapped name, normal cookie functionality resumes.

当我在我的主机文件中映射同一页面并通过映射名称打开同一页面时,正常的 cookie 功能会恢复。

  1. Open you hosts file as admin. (usually c:\windows\system32\drivers\etc\hosts)
  2. Add 127.0.0.1 localhostdevelopment.comor similar to the end of your hosts file
  3. Save your hosts file (will be rejected if you did not open the file as admin)
  4. Go to http://localhostdevelopment.com/(or whatever you called it) in Chrome.
  5. Please enjoy having your cookies behave normally.
  1. 以管理员身份打开主机文件。(通常c:\windows\system32\drivers\etc\hosts
  2. 127.0.0.1 localhostdevelopment.com在 hosts 文件末尾添加或类似
  3. 保存您的主机文件(如果您没有以管理员身份打开文件,将被拒绝)
  4. 在 Chrome 中转至http://localhostdevelopment.com/(或任何您称之为的名称)。
  5. 请享受您的 cookie 正常运行。

回答by AlphaMale

It works fine for me but Once again Make sure if your JSand Cookiesare enabled in browser. Your should check whether you cookie is setting properly or not using if(document.cookie), it will then be easier for you debugging where the problem is. Maybe you're cookies are not written properly. Please do consider the following code.

它对我来说很好,但再次确保您的JSCookies是否在浏览器中启用。您应该检查您的 cookie 设置是否正确使用if(document.cookie),然后您可以更轻松地调试问题所在。也许你的 cookie 没有正确写入。请考虑以下代码。

Write the Cookie

写饼干

Use the following code to write your cookie:

使用以下代码编写您的 cookie:

<script language="JavaScript">
 cookie_name = "Basic_Cookie";
 function write_cookie() {
 if(document.cookie) {
 index = document.cookie.indexOf(cookie_name);
 } else {
 index = -1;
 }

 if (index == -1) {
 document.cookie=cookie_name+"=1; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
 } else {
 countbegin = (document.cookie.indexOf("=", index) + 1);
 countend = document.cookie.indexOf(";", index);
 if (countend == -1) {
 countend = document.cookie.length;
 }
 count = eval(document.cookie.substring(countbegin, countend)) + 1;
 document.cookie=cookie_name+"="+count+"; expires=Wednesday, 01-Aug-2040 08:00:00 GMT";
 }
 }
 </script>

Read Your Cookie

阅读你的饼干

Once you've written the cookie, you need to read it in order to use it. Use this script to read your cookie:

一旦你写了cookie,你需要阅读它才能使用它。使用此脚本读取您的 cookie:

<script language="JavaScript">
 function gettimes() {
 if(document.cookie) {
 index = document.cookie.indexOf(cookie_name);
 if (index != -1) {
 countbegin = (document.cookie.indexOf("=", index) + 1);
 countend = document.cookie.indexOf(";", index);
 if (countend == -1) {
 countend = document.cookie.length;
 }
 count = document.cookie.substring(countbegin, countend);
 if (count == 1) {
 return (count+" time");
 } else {
 return (count+" times");
 }
 }
 }
 return ("0 times");
 }
 </script>

Call Your Cookie in a Link

在链接中调用您的 Cookie

Set your cookie when someone clicks a link with this code in your HTML body:

当有人点击 HTML 正文中包含此代码的链接时,设置您的 cookie:

<script language="javascript">document.write(gettimes());</script>

Reference: Simple Cookie Read & Write

参考:简单的 Cookie 读写

Hope this helps.

希望这可以帮助。

回答by lfree

Just change the URL from the loopback network interface to the address of the NIC of your LAN will do the work, e.g.

只需将环回网络接口的 URL 更改为 LAN 网卡的地址即可完成工作,例如

http://localhost:8080 -> http://192.168.1.15:8080 

回答by Steve Smith

Use HTML5 Local Storageinstead:-

改用HTML5 本地存储:-

<HTML>
    <HEAD>
        <TITLE>Hello World</TITLE>
    </HEAD>
    <BODY>
        <SCRIPT type="text/javascript">
            localStorage.setItem("myCookie", "ding=dong");
        </SCRIPT>
        <script type="text/javascript">
            alert(localStorage.getItem("myCookie"));
        </script>
    </BODY>
</HTML>