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.
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.
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 .
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.
Yes, Session management is done using a kind of session-id i.e. cookies. cookies maintained in the browser help backend to identify users.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With