How do you deal with cookies with JavaScript

Javascript cookies

Gives websites a memory: the cookie

Desktop applications such as Word or Photoshop remember which document was last opened, where which toolbars were and which font we prefer to use.

The HTTP protocol, on the other hand, is stateless and has no memory. Even when we come to a website for the second, third or hundredth time, the HTML page does not remember us. Without cookies, we would have to log in to Pinterest and Twitter every time and on every page. Your own blog would never notice that we are logged in and prefer to work without a graphical editor.

Name, key value + + | | document.cookie = "lastPosition =" + cookieValue; "max-age = 60 * 60 * 24 * 3; // maximum storage time path = /; // path domain = www.mysite.de"; // Cookie domain

document.cookie creates, reads and deletes cookies that form a memory for the application: for user behavior, shopping carts and individual settings. Cookies store up to 4 KB, and according to the RFC 6265 specification, a browser should store up to 3000 cookies.

Cookie information

Cookies look like strings, but are pairs of a key or name and a value that are stored in the visitor's browser. When we visit the site again later, Javascript reads in the cookie that the visitor has logged in or logged in and last looked for waffle irons, chainsaws or Javascript cookies.

comment (optional)
Can inform the user about the use of cookies.
domain (optional)
The domain name of the website. If a cookie is placed on a subdomain like blog.myhome.me is only valid in the subdomain. In order for a cookie to apply to all subdomains of a domain, domain = myhome.me set.
If the domain name is given, the domain must be written with at least two periods. If the URL is e.g. www.meineseite.de, the domain name must be given with .meineseite.de or buch.meineseite.de.
HttpOnly
indicates that the cookie is not available for Javascript. HttpOnly is set in the HTTP response, i.e. on the server side. If dynamic values ​​are required, a request can be directed to the server using Ajax.
max-age
Replaces the obsolete expires. Duration of the cookie. If no time is set (in seconds, e.g. 60 * 60 * 24 * 3 - 3 days), the cookie expires as soon as the visitor closes the browser.
path
The path to the page that is setting the cookie. Cookies normally apply to websites in the current directory and its subdirectories. A cookie that myhome.me/archiv/page.html is set, also applies to myhome.me/archiv/andereseite.html and myhome.me/archiv/daily/hierauch.html, but not to myhome.me/tags/hiernicht.html. If the path is not set or path = /, the cookie can be read from any URL on the page.
secure
If the value is the string secure contains, the cookie can only be read by a secure server (via HTTPS). If the flag remains empty, there is no restriction.
version (decimal, integer)
Version of the cookie specification (version = 1)
expires
The old format of the expiration date is superfluous, but is still supported by all browsers. Instead of expires is the easier one max-age kicked.

Third party cookies

Only the page that has set a cookie can read the cookie.

The information that a cookie brings with it remains hidden even from the user of the site.

By default in most browsers, only one page that we visit can leave a cookie in the visitor's browser. Third-party cookies - typically advertising on the visited page or an attempt at online tracking by third parties - we typically receive from iFrames that are embedded in the website using Javascript.

In Chrome we see the cookies of a page in the console (under More Tools / Developer Tools / Application):

Session cookies and persistent cookies

If the cookie does not have an expiration date (max-age or expires), it is saved as a Session cookie designated. Session cookies are not transferred to the user's hard drive. As soon as the browser window is closed, the visitor has forgotten the cookie.

Session cookies can also be set if cookies are deactivated in the visitor's browser and are set if the cookie is to be deleted and forgotten at the end of the session. This happens, for example, with online banking, so that nobody can resume the session and carry out transactions after closing the browser window.

A session cookie usually only contains a session identifier such as yuho23991uuyiao93, which is as long as possible and as random as possible. The session data is saved on the server using the session ID.

Persistent cookies (long-lived cookies), on the other hand, are stored in the visitor's browser until the visitor manually deletes them or their time has expired (expires) is.

Generate cookies

Javascript sets the cookie in the property cookie of the document object as a string. Cookies have no properties or methods, so everything is manual work if no library is activated.

document.cookie = "theme = blue twenty; max-age = 86400; path = /; domain = myhome.me"
  • After a name-value pair there is a semicolon, possibly followed by a space,
  • followed by the period of validity max-age, Semicolon, again possibly followed by a space,
  • at the end there is the cookie path and the cookie domain.

The name of the cookie is of course required and must not contain a semicolon, equal sign, comma or blank (space). The cookie value, on the other hand, is optional. mycookie =; so is correct.

The values ​​of cookies cannot contain semicolons, commas or spaces. That is why the value is coded with Javascript before saving in the cookie encodeURIComponent (). Before the cookie can be read, it must be with decodeURIComponent () can be decoded.

Overwrite cookies

Javascript cookies may look like strings, but they are not strings. If another cookie is set:

document.cookie = 'nickname = ducklings; max-age = 60 * 60 * 24 * 30; path = / ";

then this cookie does not overwrite the first cookie. Would document.cookie a string, the first cookie would have been overwritten. But it won't ... Instead, cookies are collected in the cookie string and when a specific cookie is read out, the name of the cookie must be filtered out.

Only a second cookie with the same name, path and domain would overwrite the first cookie. If, on the other hand, the path or domain are different, there are two cookies with the same name. That is seldom wanted that way.

Cookies enabled?

The script tests with Window Navigator whether cookies are deactivated or allowed and then sets a cookie as a final check whether the cookie just created exists.

function cookiesEnabled () {let cookieEnabled = (navigator.cookieEnabled)? true: false; if (typeof navigator.cookieEnabled == "undefined" &&! cookieEnabled) {document.cookie = "testcookie"; cookieEnabled = (document.cookie.indexOf ("testcookie")! = -1)? true: false; } return (cookieEnabled); }

And what if the user disabled Javascript?

There is also the noscript tag for alternative markup and content that is displayed if the user has disabled javascript.

PHP can also be used to check whether cookies are allowed or deactivated.

Cookies without Javascript?

Previously, cookies could also be generated with simple HTML in a meta tag with the http-equiv attribute.

<meta http-equiv="set-cookie" content="myCookie=Ich%20bin%20ein%20Cookie%20ohne%20Javascript">

More about cookies without Javascript Setting a Cookie Using Only HTML

And PHP can of course also set cookies:

setcookie (name, value, expire, path, domain, secure, httponly);

Cookies with httponly cannot be read with Javascript, a safety precaution against Cross Site Scripting (XSS). Google Chrome 65 dropped support for http-equiv = "set-cookie" back in March 2018 and Firefox wants to follow suit.

Local storage and session storage

Basically - as the standard says - browsers should neither limit the number of cookies nor their size as far as the memory of the browser allows. The payload of cookies is at least 4 KB and a browser should store at least 300 cookies, at least 20 cookies per host or domain name (HTTP State Management Mechanism). If you look at the cookies in your browser, you will notice that hundreds of cookies are already gathered under the letter "A".

Reading out cookies leads to a complex transfer between the browser and the server. In many processes, the actual data is not stored in the cookie itself; the cookie usually only contains a reference to data in a database on the server.

However, since the exchange of information between the script and the application is fundamental, HTML5 relies on a new concept: Local Storage and Session Storage replace the old-fashioned cookies with a memory in the user's browser and end the unencrypted traffic between the browser and the server.

External sources