108

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.

Flagbug
  • 2,093
  • 3
  • 24
  • 47
Daan Poron
  • 2,708
  • 5
  • 29
  • 33

4 Answers4

168

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

For the use case in the question (no server side code), sessionStorage is a simpler solution. But sessionStorage is client only, so would not work if you need to access the stored value on the server (e.g. user logins etc.)

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • It does not work for me and tried in many ways... Maybe this answer is outdated. – Dan May 15 '20 at 14:16
  • 1
    @Dan Session cookies doesn't work in case of enabled config: "Continue where you left off" in browser. In that cases browsers will not destroy session cookies after closing. – Taron Saribekyan Jun 16 '20 at 14:21
  • @TaronSaribekyan you are right but you have to ask all the users of your website to disable the config "Continue where you left off". Instead sessionStorage worked straight away in all the browsers. – Dan Jun 18 '20 at 08:18
  • 1
    @Rhumborl also, sessionstorage is limited to the current tab, whereas a session cookie is valid for the whole browser session – muzzletov Sep 29 '22 at 08:50
54

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.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • 1
    Yes, Session storage is the best choice for this use casE. – Julien Lafont Jan 07 '13 at 13:13
  • 19
    actually now i am using session storage ... but apparently when you open a new tab in chrome and firefox you can't access the stuff you stored in the session storage ... so that's why i was looking at session cookies: http://code.google.com/p/chromium/issues/detail?id=165452 – Daan Poron Jan 07 '13 at 13:19
  • In that case, the cookies should be reliable, although I have no idea how well-supported they are. – Cerbrus Jan 07 '13 at 13:26
  • 2
    Session (and Local) storage are affected by Same-Origin-Policy, so if you switch from http to https, you do not have access to the stuff stored in http (and visa-versa) – Jeff Lowery Apr 14 '14 at 20:15
  • 4
    I think `SessionStorage` only provides a `client-only` solution without any access to these values on server-side. In many server-side frameworks like ASP.Net and PHP, we would like to easily access the client-side values that we may have stored without using hidden fields etc., and then cookies become a better solution since cookies get automatically sent to the server-side. – Sunil Nov 06 '15 at 17:09
  • that's far from simpler, especially when there's cases in which it won't work. Then you throw in JSON also. This is simple: document.cookie = 'cookiname=cookievalue; path=/; domain=google.com; '; – Y.K. Jun 10 '16 at 22:58
  • What isn't simpler, is to get a complex value from that cookie. JSON stringify / parse is a piece of cake, compared to that. – Cerbrus Jun 10 '16 at 23:17
  • SessionStorage is awesome, but also currently broken for iOS Safari in Private mode (or with some security settings set incorrectly). Not sure if it's broken by a design decision on Apple's part though. (https://spin.atomicobject.com/2013/01/23/ios-private-browsing-localstorage/) – ToVine Jul 15 '16 at 09:28
  • @strah: How did that edit make the quote better, in any way? – Cerbrus Nov 07 '16 at 15:56
  • @Cerbrus: because someone reading your answer (and not knowing a difference between session cookies and sessionStorage) can get impression that a "session" will always behave in the same way, whereas in fact session cookies will persist between tabs/windows from the same domain, so updating the quote would make your answer complete. – strah Nov 07 '16 at 16:51
  • @strah: Not without explaining _how_ the behaviour is different. – Cerbrus Nov 07 '16 at 17:03
  • @Cerbrus: Your answer is good. My edit was a suggestion how to make it even better :-) IMHO, it *might be* a bit confusing now, but I don't insist, it's your answer. – strah Nov 07 '16 at 17:12
  • data cant be retrieved from session storage if there is new redirection to a different page. – techie_28 Jun 18 '18 at 07:06
11

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=/";
Gaurav Agarwal
  • 863
  • 7
  • 28
  • 4
    expires=0 in IE doesn't set a cookie at all: http://blog.lysender.com/2011/08/setting-session-only-cookie-via-javascript/ – JDandChips Nov 05 '14 at 12:44
  • 1
    expires="" works in IE, and allows you to reset the expiry of a cookie to Session, if you have explictly set it – koolunix Mar 02 '17 at 23:49
-1

Use the below code for a setup session cookie, it will work until browser close. (make sure not close tab)

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
  }
  function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.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) == 0) {
        return c.substring(name.length, c.length);
      }
    }
    return false;
  }
  
  
  if(getCookie("KoiMilGaya")) {
    //alert('found'); 
    // Cookie found. Display any text like repeat user. // reload, other page visit, close tab and open again.. 
  } else {
    //alert('nothing');
    // Display popup or anthing here. it shows on first visit only.  
    // this will load again when user closer browser and open again. 
    setCookie('KoiMilGaya','1');
  }