Reading Cookies using Javascript
To read cookies with Javascript:
var ko = document.cookie;
document.write(ko);
or
document.write(document.cookie);
-We named a variable
ko because it's easy to type.
-We stored the cookies in
ko
-We printed all cookies set by our domain to the browser, assuming there are some.
-The second document.write is just a shortcut.
Now, let's set two cookies first:
document.cookie="iltccook=got it ONE;domain=ilovethecode.com;expires=Mon, 18-Feb-2036 05:43:38 GMT;path=/";
document.cookie="iltccook2=got it Two;domain=ilovethecode.com;expires=Mon, 18-Feb-2036 05:43:38 GMT;path=/";
Then we'll read and split them into usable pieces.
var ko=document.cookie.split("; ");
-We split the cookies into pieces by the semicolon and space. (semicolon-space is how all browsers store multiple cookies)
-Now we'll print out their pieces.
document.write(document.cookie + "<br>");
document.write(ko[0] + "<br>");
document.write(ko[1] + "<br>");
-The first document.write prints all cookies from our domain.
-The second document.write prints the cookie at index zero (aka the first cookie).
-The third document.write prints the cookie at index one (aka the second cookie).
You could split these down further still like so:
var ji=ko[0].split("=");
-
ko[0] has our first cookie.
-We split
ko[0] by the equals sign and store the pieces in the variable we name
ji
-Now we print the pieces with four dashes in between to make it look pretty.
document.write(ji[0] + " ---- " + ji[1]);
Free Copy and Paste Javascript Code:
<script type="text/javascript">
<!--
document.cookie="iltccook=got it ONE;domain=ilovethecode.com;expires=Mon, 18-Feb-2036 05:43:38 GMT;path=/";
document.cookie="iltccook2=got it Two;domain=ilovethecode.com;expires=Mon, 18-Feb-2036 05:43:38 GMT;path=/";
var ko=document.cookie.split("; ");
document.write(document.cookie + "<br>");
document.write(ko[0] + "<br>");
document.write(ko[1] + "<br>");
var ji=ko[0].split("=");
document.write(ji[0] + " ---- " + ji[1]);
-->
</script>
Resources:
Setting a Cookie
Spltting an Array in Javascript
Click HERE to comment or discuss at iLoveTheCode GOOGLE Group
| | CSS David McFarland | |
| | | |
| | | |