Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

reading a cookie in javascript

Posted on 2014-12-09
24
66 Views
Last Modified: 2014-12-15
I have the following:

var cookie = '';

function ReadCookie(cookieName) {
      var theCookie = " " + document.cookie;
      var ind = theCookie.indexOf(" " + cookieName + "=");
      if (ind == -1) ind = theCookie.indexOf(";" + cookieName + "=");
      if (ind == -1 || cookieName == "") return "";
      var ind1 = theCookie.indexOf(";", ind + 1);
      if (ind1 == -1) ind1 = theCookie.length;
      return unescape(theCookie.substring(ind + cookieName.length + 2, ind1));
}

function checkCookie() {
      cookie = ReadCookie("test");
      if (cookie != '') {
            $(".add-info").hide();
            $("#newStartButtonWrapper").insertAfter(".add-info");
            $("#newStartButtonWrapper").show();
      } else {
            $(".add-info").show();
            $("#newStartButtonWrapper").hide();
      }
}

checkCookie();


Where I want to check for a cookie called test, if it exists then hide the #newStartButtonWrapper
but at the moment it doesn't work - can you see an issue?

No Jquery plugins
0
Comment
Question by:Al4ddin2
  • 10
  • 6
  • 4
  • +2
24 Comments
 
LVL 58

Expert Comment

by:Gary
ID: 40489351
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40489356
I don't know what's going on but one validation should be enough:
var ind = theCookie.toLowerCase().indexOf(cookieName.toLowerCase() + "=");

Open in new window

if this returns -1 is because it doesn't exist
0
 
LVL 12

Expert Comment

by:Chris
ID: 40489363
Don't you have your checkCookie() function the wrong way around? You're checking if the var cookie is NOT empty (ie. the cookie exists) then showing #newStartButtonWrapper instead of hiding.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:Al4ddin2
ID: 40489396
Gary, that fiddle - if I remove the creation of the cookie and run it again the div nevers hides.
0
 

Author Comment

by:Al4ddin2
ID: 40489397
It always shows
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489438
why not use a small plugin here?

http://plugins.jquery.com/cookie/

Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3

Get a cookie
alert( $.cookie("example") );

Delete the cookie
$.removeCookie("example");
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489450
what do you have in cookie? can you give us some samples?

I made a test and it is returning nothing...

<script>
var cookie = 'x=1234; y=456; z=abc';

function ReadCookie(cookieName) {
      var theCookie = " " + document.cookie;
      var ind = theCookie.indexOf(" " + cookieName + "=");
      if (ind == -1) ind = theCookie.indexOf(";" + cookieName + "=");
      if (ind == -1 || cookieName == "") return "";
      var ind1 = theCookie.indexOf(";", ind + 1);
      if (ind1 == -1) ind1 = theCookie.length;
      return unescape(theCookie.substring(ind + cookieName.length + 2, ind1));
}
alert('x = ' + ReadCookie('x'));
alert('a = ' + ReadCookie('a'));
alert('y = ' + ReadCookie('y'));
alert('z = ' + ReadCookie('z'));
</script>

Open in new window

0
 

Author Comment

by:Al4ddin2
ID: 40489459
The value is just a number hash and i'm not too concerned about what the value is, just if the cookie exists.
0
 

Author Comment

by:Al4ddin2
ID: 40489468
this currently outputs "no cookie" when there is one...

var cookie = '';

        function ReadCookie(cookieName) {
            var theCookie = " " + document.cookie;
            var ind = theCookie.toLowerCase().indexOf(cookieName.toLowerCase() + "=");
            if (ind == -1) {
                return "";
            } else {
                return "Cookie Found";
            }
        }

        function checkCookie() {
            cookie = ReadCookie("test");
            if (cookie == "") {
                console.log("no cookie", cookie);
                $(".add-info").show();
                $("#newStartButtonWrapper").hide();
            } else {
                console.log("cookie found", cookie);
                $(".add-info").hide();
                $("#newStartButtonWrapper").insertAfter(".add-info");
                $("#newStartButtonWrapper").show();
            }
        }

        checkCookie();

Open in new window

0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489469
i guess this code is not good

if (ind == -1) ind = theCookie.indexOf(";" + cookieName + "=");  >>> looks like redundant

I am assuming, cookies are like this:

"x=1234; y=456; z=abc"

but it is covered with this code

var ind = theCookie.indexOf(" " + cookieName + "=");

but this is not the issue right now... maybe you should check the cookie after you set it...
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489472
this currently outputs "no cookie" when there is one...

post the value of

alert(document.cookie);
0
 

Author Comment

by:Al4ddin2
ID: 40489493
hmmm, when I use firebug or another tool I can see the cookie there, however when I return document.cookie it doesn't include that cookie in there?
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489495
maybe you are using https! trying to get it on http...
or maybe you set cookies without expiry and they expire immediately and when you try to get it, there is nothing in cookies...
0
 

Author Comment

by:Al4ddin2
ID: 40489506
If I am using https does that mean I cannot access the cookies?
0
 

Author Comment

by:Al4ddin2
ID: 40489510
I'm not though... the site and cookie is on http
0
 

Author Comment

by:Al4ddin2
ID: 40489511
Any ideas why it might not be displaying?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40489528
Run this fiddle
http://jsfiddle.net/f36rwpxt/8/

Cookie is not set

Uncomment the first line and run and you get cookie is set.
0
 
LVL 51

Expert Comment

by:HainKurt
ID: 40489535
how do you set the cookie? do you add domain & expire date?
0
 

Author Comment

by:Al4ddin2
ID: 40489652
Could it be that a cookie can be set so that is not visible to the JS engine perhaps?
It is a login that creates the cookie at the moment that I do not have direct access too.
0
 
LVL 58

Expert Comment

by:Gary
ID: 40489677
How is the cookie set? Is it the same domain? When setting the domain are you just using domain.com and not www.domain.com - different sub domains do not have access to a cookie set on a different sub domain unless you remove the sub domain
So for cross domain cookies you need to add

domain=domain.com
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40489679
Ah, so if it's a login cookie probably it's a 'httponly' cookie.
This is a protection mechanism to avoid the cookie to be used in a malicious way.
https://www.owasp.org/index.php/HttpOnly

If you have no control over how the cookie is set then I believe there's no workaround.
Maybe you can set your own cookie or set an hidden field flag from the backend to accomplish the same thing.
0
 

Author Comment

by:Al4ddin2
ID: 40489751
Ah Alexandre, if it is httponly then I cannot access it?
0
 
LVL 58

Expert Comment

by:Gary
ID: 40489800
Did you set it to HTTPOnly - that is not the default for cookies.
0
 
LVL 30

Accepted Solution

by:
Alexandre Simões earned 500 total points
ID: 40489877
@Al4ddin2: No. It's a security flag exactly for that. You see it in the browser developer tools but javascript cannot read it.
You can find more info on the link I gave you.
To test if this is the case you should use the developer tools to intercept the request that sets the cookie (should be the login request) and see if the Set-Cookie header flag is setting the HttpOnly for that cookie.

@Gary: He said he has no control over the creation of the cookie... As far as I understood it comes from the authentication system. Being an authentication cookie I find it likely that this is the issue here.
0

Featured Post

Free Tool: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question