How to get session cookie via javascript?

Asked

Viewed 6,154 times

7

I need to make a script that when the user arrives at my utm via url, I must record a session cookie. This cookie will expire when the browser closes. Can anyone help me with this?

4 answers

6


To create a cookie for session, just associate a string containing the format chave=valor to the property cookie of document:

document.cookie = "[nomeDoCookie]=[ValorDoCookie]";

If you wish to persist this cookie between browser sessions, you can specify an expiration date in format Gmtstring:

document.cookie = "[nomeDoCookie]=[ValorDoCookie]; expires=[data]";

Examples:

document.cookie = "cookie2=sample";
document.cookie = "cookie2=true; expires=Fri, 31 Dec 9999 23:59:59 GMT";

However it is worth mentioning that there is no guarantee that the session cookie will be waived when all windows are closed - Chrome, for example, has a setting that by default keeps session cookies alive:

inserir a descrição da imagem aqui

Sources:
MDN - Document cookie.
Stackoverflow - Chrome doesn’t delete Session cookies

3

2

To create the cookie:

  document.cookie = "username=[utilizador]; expires=[dia que expira], [18 Dec 2013 12:00:00 UTC]";

To read the cookie:

var x = document.cookie;

2

Marcos,

in accordance with wikipedia, to do what you want should be created a cookie Session, which is nothing more than a cookie with no expiration date.

When you create the cookie with no expiration date, it is only in memory and once the browser is closed the cookie is removed.

A Session cookie, also known as an in-memory cookie or Transient cookie, exists only in Temporary memory while the user navigates the website. [12] Web browsers normally delete Session cookies when the user closes the browser. [13] Unlike other cookies, Session cookies do not have an expiration date Assigned to them, which is how the browser Knows to Treat them as Session cookies.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.