Session only cookies with Javascript
I was wondering if it's possible to create session only cookies with Javascript. When the browser is closed the cookies should be removed.
I can't use anything on the server as the website is HTML only ... so no server side script is used.
I read something about this here: http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ but i can't find any more information about this ... so i was wondering if this method is reliable.
Yes, that is correct.
Not putting an expires
part in will create a session cookie, whether it is created in JavaScript or on the server.
See https://stackoverflow.com/a/532660/1901857
A simpler solution would be to use sessionStorage
, in this case:
var myVariable = "Hello World";
sessionStorage['myvariable'] = myVariable;
var readValue = sessionStorage['myvariable'];
console.log(readValue);
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);
var readValue = JSON.parse(sessionStorage['myvariable']);
A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
So, when you close the page / tab, the data is lost.
For creating session only cookie with java script, you can use the following. This works for me.
document.cookie = "cookiename=value; expires=0; path=/";
then get cookie value as following
//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 "";
}
Okay to support IE we can leave "expires" completely and can use this
document.cookie = "mtracker=somevalue; path=/";