Write Local Storage data into Cookie via JavaScrip

2019-08-04 06:45发布

I have been tasked with copying a particular value from a chosen key in the browsers local storage into the cookie for the website; the browser being used is Safari.

This particular value contains the users logon details, as the browser on the device will only ever be used by one person the designer is happy with keeping this sort of sensitive information in the browsers local storage.

My question is how would I go about populating the cookie with the correct data using Javascript?, possibly using JSON to store the data initially.

Thanks for your time.

2条回答
贼婆χ
2楼-- · 2019-08-04 07:10

You can also use a jQuery cookie plugin

$.cookie(
    'username', 
    localStorage.getItem('username'), { 
        expires: 7, 
        path: '/', 
        domain: 'jquery.com', 
        secure: true 
});
查看更多
一夜七次
3楼-- · 2019-08-04 07:23

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 will expire in 7 days. Change the '7' (there's only one there) to however many days you want. To store other keys just change the two occurrences of 'username' in the above code to whatever the name of the variable is ('password', for example).

查看更多
登录 后发表回答