Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 382
Daan Poron Avatar asked Jan 07 '13 13:01

Daan Poron


People also ask

What is session cookies in JavaScript?

Session only cookies, on the other hand, stores information in the browser memory, and is available for the duration of the browser session. In other words, the data stored inside a session cookie is available from the time of storage until the browser is closed.

Can JavaScript create HttpOnly cookie?

Answer. A HttpOnly cookie means that it's not available to scripting languages like JavaScript. So in JavaScript absolutely no API available to get/set the HttpOnly attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly .

Can you access cookies using JavaScript?

You are most likely dealing with httponly cookies. httponly is a flag you can set on cookies meaning they can not be accessed by JavaScript.

Can we use cookies as session?

Yes, Session management is done using a kind of session-id i.e. cookies. cookies maintained in the browser help backend to identify users.


2 Answers

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

like image 53
Rhumborl Avatar answered Oct 21 '22 16:10

Rhumborl


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.

like image 39
Cerbrus Avatar answered Oct 21 '22 16:10

Cerbrus