Solved

reading a cookie in javascript

Posted on 2014-12-09
24
62 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
 

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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
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

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Suggested Solutions

Today I would like to talk about localizing (Internationalization) JavaScript applications. Introduction When creating an application that is going to be used by many people around the globe, it is important to remember that not everyone speak…
In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
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…

760 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now