localStorage、sessionStorage、cookie

localStorage

  • 在浏览器中存储数据,数据无过期时间,浏览器关闭后数据不会丢失,除非手动删除
  • 通常为5MB左右(因浏览器而异)
  • 数据在同源的所有页面中共享
  • 适合存储用户设置等长期数据
  • 只能前端操作
  • 键值对格式
localStorage.setItem(key, JSON.stringify(data));
localStorage.getItem(key);
localStorage.removeItem(key);
localStorage.clear();

localStorage手动设置过期时间

localStorage本身不支持过期时间,但可以通过存储时间戳来实现

function set() {
    const item = {
        key: 'name',
        value: '张三',
        expires: new Date().getTime() + 7 * 24 * 60 * 60 * 1000,
    }
    localStorage.setItem(item.key, JSON.stringify(item));
}

function get() {
    const item = JSON.parse(localStorage.getItem('name'));
    if(new Date().getTime() > item.expires) {
        localStorage.removeItem(key);
        return null;
    }
    return item.value;
}

sessionStorage

  • 用于存储数据,仅在当前会话中有效,窗口或标签页关闭后数据清除
  • 通常为5MB左右,因浏览器而异
  • 数据仅在同一标签页中可用,不同标签页无法共享
  • 适合存储临时数据
  • 只能前端操作
  • 键值对格式
sessionStorage.setItem(key, JSON.stringify(data));
sessionStorage.getItem(key);
sessionStorage.removeItem(key);
sessionStorage.clear();

注意:

  • 通过带target="_blank"的a标签打开新窗口,不会携带旧窗口的sessionStorage;
    之前是会携带的,但由于容易引起安全漏洞,在2021年,更改规格之后就不会携带了
  • 通过window.open(),会打开一个新窗口或标签页,会把旧窗口的sessionStorage携带过来
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>test1</title>
</head>
<body>
    <a href="./test2.html">去test2</a>
    <br />
    <a href="./test3.html" target="_blank">去test3</a>
    <div class="test4">去test4</div>
    <div class="test5">去test5</div>
    <script>
        sessionStorage.setItem("name", "张三");

        // window.location.href 会在当前窗口或标签页中加载新页面,替换当前页面
        // 相当于 target="_self"
        document.querySelector('.test4').addEventListener('click', function() {
            window.location.href = 'test4.html';
        });
        document.querySelector('.test5').addEventListener('click', function() {
            window.open('test5.html');
        });
    </script>
</body>
</html>

在子窗口获取父窗口可通过window.opener获取引用

通过window.open()打开新窗口,window.opener保留了旧窗口的引用

通过带target="_blank"的a标签打开新窗口,window.opener = null,因为默认会指定rel="noopener",我们可以通过修改rel="opener",获取到旧窗口的sessionStorage

https://developer.mozilla.org/zh-CN/docs/Web/HTML/Attributes/rel

<a href="./test3.html" target="_blank" rel="opener">去test3</a>

cookie

  • 存储在用户计算机上,可以设置过期时间
  • 每个cookie大小限制在4KB,且每个域名最多存储cookie个数有限(具体个数说法不一致,有20、50等,大概根据浏览器而异)
  • 可以设置特定路径和域名,支持跨页面使用
  • 适合存储用户身份信息等
  • 前后端都能操作
  • 字符串格式

cookie的使用

// cookie.js
const doc = document;

export default {
    set(name, value, domain, path, expires) {
        if (expires) {
            expires = new Date(Date.now() + expires);
        }
        const cookieParts = [
            `${name}=${encodeURIComponent(value)}`,
            expires ? `expires=${expires.toGMTString()}` : '',
            path ? `path=${path}` : '',
            domain ? `domain=${domain}` : ''
        ].filter(Boolean);
        const cookieString = cookieParts.join('; ');
        if (cookieString.length < 4096) {
            document.cookie = cookieString;
        }
        return this;
    },


    get(name) {
        const match = doc.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
        return match ? decodeURIComponent(match[1]) : null;
    },

    del(name, domain, path) {
        if (this.get(name)) {
            const cookieString = `${name}=; expires=Thu, 01-Jan-1970 00:00:01 GMT` +
                (path ? `; path=${path}` : '') +
                (domain ? `; domain=${domain}` : '');
            doc.cookie = cookieString;
        }
        return this;
    }
    
};
// use.js
import cookie from './cookie';
cookie.set(key, val, location.hostname, '/', 7 * 24 * 60 * 60 * 1000);
cookie.get(key);
cookie.del(KF_ROBOT_ID, location.hostname, '/');

  • 14
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值