Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 80
  • Last Modified:

reading a cookie in javascript

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
Al4ddin2
Asked:
Al4ddin2
  • 10
  • 6
  • 4
  • +2
1 Solution
 
GaryCommented:
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
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
 
ChrisCommented:
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
Al4ddin2Author Commented:
Gary, that fiddle - if I remove the creation of the cookie and run it again the div nevers hides.
0
 
Al4ddin2Author Commented:
It always shows
0
 
HainKurtSr. System AnalystCommented:
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
 
HainKurtSr. System AnalystCommented:
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
 
Al4ddin2Author Commented:
The value is just a number hash and i'm not too concerned about what the value is, just if the cookie exists.
0
 
Al4ddin2Author Commented:
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
 
HainKurtSr. System AnalystCommented:
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
 
HainKurtSr. System AnalystCommented:
this currently outputs "no cookie" when there is one...

post the value of

alert(document.cookie);
0
 
Al4ddin2Author Commented:
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
 
HainKurtSr. System AnalystCommented:
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
 
Al4ddin2Author Commented:
If I am using https does that mean I cannot access the cookies?
0
 
Al4ddin2Author Commented:
I'm not though... the site and cookie is on http
0
 
Al4ddin2Author Commented:
Any ideas why it might not be displaying?
0
 
GaryCommented:
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
 
HainKurtSr. System AnalystCommented:
how do you set the cookie? do you add domain & expire date?
0
 
Al4ddin2Author Commented:
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
 
GaryCommented:
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
 
Alexandre SimõesManager / Technology SpecialistCommented:
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
 
Al4ddin2Author Commented:
Ah Alexandre, if it is httponly then I cannot access it?
0
 
GaryCommented:
Did you set it to HTTPOnly - that is not the default for cookies.
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
@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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 10
  • 6
  • 4
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now