Writing Local Storage Data to Cookie via JavaScript

I have been instructed to copy a specific value from the selected key in the local browser store to the cookie for the website; The browser used is Safari.

This specific value contains information about users logging in, since the browser on the device will be used by only one person, the developer is pleased to keep this kind of confidential information in the local browser store.

My question is how can I replenish cookies with the correct data using Javascript ?, possibly using JSON for initial data storage.

Thank you for your time.

+1
source share
2 answers

Assuming the key in localStorage is "username":

document.cookie='username=' + localStorage.getItem('username') + 'expires='+new Date((new Date().getTime()) + 1000*60*60*24*7).toGMTString() +'; path=/'; 

This cookie expires in 7 days. Change "7" (there is only one) for as many days as you like. To save other keys, simply change the two occurrences of the "username" in the above code to what the variable name is (for example, "password").

+1
source

You can also use jQuery cookie plugin

 $.cookie( 'username', localStorage.getItem('username'), { expires: 7, path: '/', domain: 'jquery.com', secure: true }); 
0
source

Source: https://habr.com/ru/post/1412471/


All Articles