Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript document.cookie = "key=value" appends instead of replacing

Came across this syntax of adding new key in cookie on a browser:

document.cookie = "key=value";

which appends this value in document.cookie instead of replacing the old value which is the operation it should be doing in default scenario.

How is this string behavior achieved i.e. over-riding the default operation?

like image 397
Aman Gupta Avatar asked Apr 15 '26 23:04

Aman Gupta


1 Answers

This is how cookies in JavaScript have always worked.

document.cookie = "key=value";
document.cookie; // "key=value"

document.cookie = "key=value2";
document.cookie; // "key=value2"

document.cookie = "key2=valuex";
document.cookie; // "key=value2;key2=valuex"

The original key is only overwritten if it is specified again. Cookies are weird and counter-intuitive because regardless of how many cookies for the domain are set, there is only ever one value for document.cookie - a single string

like image 84
danwellman Avatar answered Apr 18 '26 13:04

danwellman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!