Session cookie only with javascript

I was wondering if it is possible to create session cookies with Javascript. When the browser is closed, cookies must be deleted.

I can’t use anything on the server since the website is only HTML ... therefore the server side of the script is not used.

I read something about it here: http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ but I can not find more information about it ... so I I was wondering if this method is reliable.

+46
javascript html html5
Jan 07 '13 at 13:09
source share
3 answers

Yes, it's right.

Without placing the expires part, it will create a session cookie, regardless of whether it is created in JavaScript or on the server.

See https://stackoverflow.com>

+83
Jan 07 '13 at 13:13
source share

A simpler solution would be to use sessionStorage , in this case:

 var myVariable = true; sessionStorage['myvariable'] = myVariable; myVariable = sessionStorage['myvariable']; 

However, keep in mind that sessionStorage saves everything as a string, so when working with arrays / objects, you can use JSON to store them:

 var myVariable = {a:[1,2,3,4], b:"some text"}; sessionStorage['myvariable'] = JSON.stringify(myVariable); myVariable = JSON.parse(sessionStorage['myvariable']); 

A page session lasts as long as the browser is open and survives reloading and restoring the page. Opening a page in a new tab or window will start a new session.

So, when you close the page / tab, the data is lost.

+32
Jan 07 '13 at 13:12
source share

To create a cookie with only java script, you can use the following. This works for me.

 document.cookie = "cookiename=value; expires=0; path=/"; 

then get the cookie value as

  //get cookie var cookiename = getCookie("cookiename"); if (cookiename == "value") { //write your script } //function getCookie function getCookie(cname) { var name = cname + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') c = c.substring(1); if (c.indexOf(name) != -1) return c.substring(name.length, c.length); } return ""; } 

It’s good to support IE, we can leave "definitively" and use this

 document.cookie = "mtracker=somevalue; path=/"; 
+7
Aug 18 '14 at 16:17
source share



All Articles