X
Publisher: Sigit purnomo kangsigit.com@gmail.com

How To Use Cookies in Javascript to Blogger

Below is a simple script that has three functions: the first is to set a cookie, the second is to read and store for a certain duration, and the last is to remove it.

This is not limited to your use Blogger, can also be applied to paid hosting and free hosting such as wordpress and others.

Advertisement

Here are the steps to apply a cookie on Blogger

  • Sign in HTML Template
  • Find </head> and enter this javascript thereon.
<script type='text/javascript'>
//<![CDATA[
// Set cookie
function setCookie(name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
// Read cookie
function getCookie(name){
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
//delete cookie
function eraseCookie (name,path,domain) {
if (getCookie(name)) {
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
//]]>
</script>
  • Still in the HEAD section, please set the expiration date by changing the number 10000 (in milliseconds)
<script>
var expiration = new Date();
expiration.setTime(expiration.getTime() + 10000); //Expire after 10 seconds
setCookie("cookiename","hello",expiration);
}
</script>

Advertisement

  • The code above to get the cookie value to 10000 milliseconds or 10 seconds. If we want to restore the value of this cookie, then we should use the second function with CookieName:
<script>var checkCookie = getCookie("cookiename");</script>
  • Then, add this javascript code above </body>
<script type='text/javascript'>
var expiration = new Date();
expiration.setTime(expiration.getTime() + 10000);
setCookie("cookiename","hello",expiration);
var checkCookie = getCookie("cookiename");
document.write(checkCookie);
</script>
How To Use Cookies in Javascript to Blogger
Add Comments
0 Comments
Click Here to Add Comments

No Comment