Cannot set cookies in Javascript
Asked Answered
A

10

48

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.

<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>
Accentual answered 12/11, 2011 at 14:43 Comment(3)
Setting and reading the cookie work fine for me.Roberson
doesn't work for me. I get blank alert from your link. I check under resource and there were no cookies. This is intriguing me..Accentual
#8105635Fennell
N
132

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.

Nannie answered 27/9, 2012 at 9:26 Comment(10)
This right here is the answer; it'd be nice if OP would mark it as such.Inbreeding
Same on Google Chrome v38.Tades
This is a whack answer. Thank you whoever ensured that this was the way things were.Decalcify
Actually the answer is great, I just mean the actual logic behind the answer is trash.Decalcify
As an alternative to cookies you can try using HTML5 Local Storage which work even when accessed via file:///.Utter
Unfortunately (confusingly) window.localStorage is blocked by Chrome's "block third-party cookies" setting for pages run from file:/// but not from http://.Kandace
then how do local servers save cookies to browser for saving sessionVignette
It would be a better answer if it told us how to store Cookies that worked locally.Helio
In my case i was trying to store a cookie which exceeded the max browser size of 4096 bytes per cookieImpose
Chrome will store cookies locally, but you have to be running a server and do it on something like localhostAntipode
D
8

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:

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:

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

Decree answered 14/4, 2013 at 10:55 Comment(0)
L
7

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.

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+";";
}
Lykins answered 8/11, 2013 at 13:33 Comment(3)
Developers should understand the implications of doing such a thing, unless they truly need a "just works" solution for some homework or related. There are other cookie values that may or may not require setting. Please visit en.wikipedia.org/wiki/HTTP_cookie and understand cookies.Decalcify
Perfect solution, This was the solution I was looking for so many days.Britannic
@John Castell : Thanks for the solution above, I too had the same problem and removing the path and domain worked for me, however I am still curious as to why this worked now and what hindrance do the path and domain parameter cause. I must admin I was facing the issue only in http protocols, https worked fine for me even with path and domain parameter.Vituperate
A
3

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:

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

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

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

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

Alduino answered 5/2, 2015 at 17:5 Comment(1)
I got the "<my-computer-name> refused to connect." error message.Kathe
S
2

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

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

  1. Open you hosts file as admin. (usually c:\windows\system32\drivers\etc\hosts)
  2. Add 127.0.0.1 localhostdevelopment.com or 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.
Staciastacie answered 11/4, 2013 at 9:51 Comment(2)
Remember that if we use this approach that the host name must end in a tld to actually trick chrome.Decalcify
And, if you use domain=xxx on your cookie, be sure that your "local domain" matches that. (E.g. if you are developing something for example.com and hence set domain=example.com, then adding local.example.com to your hosts file should work.)Billfish
M
2

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

Moluccas answered 11/9, 2017 at 4:43 Comment(0)
V
1

It works fine for me but Once again Make sure if your JS and Cookies are 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.

Write the Cookie

Use the following code to write your 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:

<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

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

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

Reference: Simple Cookie Read & Write

Hope this helps.

Valladares answered 12/11, 2011 at 14:55 Comment(4)
thanks. Tried. and doesn't work. Blank. I know javascript and cookie is enabled and worked on my browser. So I have no idea what's going on. There's no where I can look to debug either..Accentual
change your browser..... Try it in IE or Chrome or FF. give it a go in any other browser. May be it will work. because it is working for me and there is no apparent issue in your code.Valladares
i tried FF, Chrome, and Safari (I develop on Mac). doesn't work. Is there anyway I can debug what's going on?Accentual
Set cookie expires time also, dbp-consulting.com/tutorials/web/jscookies.htmlValladares
H
0

Use HTML5 Local Storage instead:-

<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>
Helio answered 6/9, 2018 at 14:47 Comment(0)
K
0

Chrome has some stricter cookie policies.

  1. If you run in Chrome locally, It doesn't allow you to set cookies.
  2. If you run in Firefox or other browsers locally, they allow you.
  3. If you run in Chrome the same project in a host, Chrome allows you.

but if you want to check your project locally and need to set cookies in Chrome you can play a trick. you can run a server using Python or node.js easily.

  1. Go to your HTML directory
  2. run this command > python -m http.server
  3. Type in Chrome http://localhost:8000/test.html
  4. Now you can set cookies in Chrome locally

Note: (if the Python command isn't working, it means Python isn't in the path you can set the path in Environment or you can use the full path of python.exe)

Good luck

Khan answered 23/6 at 16:11 Comment(0)
I
-2

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

http://localhost:8080 -> http://192.168.1.15:8080 
Ilysa answered 26/9, 2017 at 6:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.