4

I have some code that creates cookies. It creates two different user groups, checks for what group the users cookie is and does something based on it.

The code is being developed on a local machine so it is accessed through a file:/// URL

It looks like this:

function cookieCreation() {
                var groupId = Math.floor(Math.random() * 2) + 1;
                var expDate = new Date(new Date().getTime()+60*60*1000*24).toGMTString()
                document.cookie = "userGroup_" + groupId + ";" + "expires=" + expDate +";path=/";
            }

            function getCookie(cname) {
                var name = cname + "=";
                var ca = document.cookie.split(';');
                    for(var i = 0; i < ca.length; i++) {
                        var c = ca[i];
                            while (c.charAt(0) == ' ') {
                                c = c.substring(1);
                            }
                        if (c.indexOf(name) == 0) {
                            return c.substring(name.length, c.length);
                        }
                    }
                return "";
            }

            function cookieBasedPush() {
                cookieCreation();
                var currentCookie = getCookie("userGroup_1");

                if (currentCookie == null) {
                    console.log("User Group 2");
                } else {
                    console.log("User Group 1");
                }
            }

            window.onload = cookieBasedPush;

A cookie looks like it is being created because I can see "User Group 1" is being console logged. However, when I run document.cookie, I get nothing.

I searched and found Setting Cookies using JavaScript in a local html file and based on this answer, suggests that cookies can't be created in a file:/// URL.

That is what confuses me and doesn't make any sense - If that is the case, then why am I getting a successful console.log of the user group 1 cookie creation? Why is document.cookie blank when run in console? Is my logic not right in code?

halfer
  • 19,824
  • 17
  • 99
  • 186
kawnah
  • 3,204
  • 8
  • 53
  • 103

1 Answers1

3

Cookies are strictly a HTTP mechanism as per RFC 2109.

See this link, here, for the chrome "bug" report of this.

You can, however, run chrome with the flag --enable-file-cookies to allow file:/// cookies

To run chrome with experimental / developer flags have a look here for instructions

It appears that the --enable-file-cookies flag has been removed from all platforms that chrome runs on except Android. You can read more about it here and here.

With this, it appears that there is no way to store cookies under a file:/// URL structure, The best way to go around this would be to run a small server locally when developing. Here's a good list of scripts that can run a local HTTP server from the command line. link

Jack
  • 649
  • 7
  • 22
  • Ok - so keeping that in mind, why would this code consolelog "User Group 1" if cookies are disabled on `file:///`? what is my logic flaw? – kawnah Nov 21 '17 at 16:41
  • You are still getting the log `"User Group 1"` because you're checking if the returned value in the function `getCookie()` (That is an empty string) is equal to `null`, For a start, You don't need to have a `return` to the end of a function, secondly, `null` is NOT equal to `""`. Have a look here to learn about datatypes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures | Also, when checking if something is "equal" to something, make sure to use type-safe equality operators, `===` and `!==` instead of their regular counterparts `==` and `!=`. – Jack Nov 21 '17 at 17:17
  • I'm having a hard time getting it so I apologize in advance. So that means a cookie is being generated then, right? Because if it was null it would return User Group 2 (which I'm realizing is a flaw but that I'll try to work out later) I made changes suggested so changed checking for null to check for `""` in the `cookieBasedPush()` function, deleted retrun and am using the type-safe operator, so `===` but I still get User Group 1. – kawnah Nov 21 '17 at 17:51
  • Have a look at my answer, I've updated it to correct my previous mistake with regards to running chrome with said flag. – Jack Nov 21 '17 at 17:54
  • There should be no cookies then and it should always be null. It can't be `null` if I'm getting User Group 1, correct? – kawnah Nov 21 '17 at 17:54
  • At this point, the question is more as to why this code isn't working for you, I think that there is no point debugging the script in its current state, You need to do some reading up in terms of cookies, While this (https://www.w3schools.com/js/js_cookies.asp) W3 Schools article is good, simply copying code isn't going to help you learn, The code that you copied is not very applicable for any real use, If you outline your needs and what you want to use this script for you can email me here; https://voidtyphoon.co.uk/email/stackoverflow and I'll be more than happy to help you there :) – Jack Nov 21 '17 at 18:13
  • Alright I may send you a note later - it's not that I don't know about cookies or anything. I'll try to pick at this later. – kawnah Nov 21 '17 at 18:57
  • Sure thing, The code seems like it might be confusing you was my only concern, a different approach might be better as it won't be so tightly packed together in functions as this is :) – Jack Nov 21 '17 at 19:05