通过JavaScript将本地存储数据写入Cookie



我的任务是将浏览器本地存储中选定的密钥中的特定值复制到网站的cookie中;所使用的浏览器是Safari。

此特定值包含用户登录详细信息,因为设备上的浏览器只能由一个人使用,因此设计者很乐意将此类敏感信息保存在浏览器的本地存储中。

我的问题是,我该如何使用Javascript用正确的数据填充cookie?,可能最初使用JSON来存储数据。

谢谢你抽出时间。

假设localStorage中的密钥是"username":

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

此cookie将在7天后过期。将"7"(只有一个)更改为您想要的天数。要存储其他键,只需将上面代码中出现的两个"username"更改为变量的名称(例如"password")。

您还可以使用jQuery cookie插件

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

最新更新