通过JavaScript将本地存储数据写入Cookie [英] Write Local Storage data into Cookie via JavaScript

查看:260
本文介绍了通过JavaScript将本地存储数据写入Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

感谢您的时间.

推荐答案

假定localStorage中的密钥为'username':

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=/';

此Cookie将在7天后过期.将"7"(那里只有一个)更改为您想要的任意天数.要存储其他键,只需将上面代码中两次出现的用户名"更改为变量名(例如密码")即可.

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).

这篇关于通过JavaScript将本地存储数据写入Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆