普通视图

发现新文章,点击刷新页面。
昨天 — 2025年12月21日首页

前端跨页面通讯终极指南⑧:Cookie 用法全解析

2025年12月21日 20:57

前言

之前介绍了很多前端跨页面通讯的方案,今天介绍下Cookie,Cookie自身有“同源共享”的特性,但因为缺少数据变化的主动通知机制,只能使用“轮询”弥补这一缺陷。

本文将使用Cookie轮询,进行跨页面通讯。

1. Cookie 轮询基本原理

Cookie轮询通过“存储-定期检查-差异处理”的核心逻辑实现跨页面通讯,具体流程为:

  1. 一个页面将消息(如状态、指令等)结构化后存储到Cookie中;
  2. 其他同源页面通过定时任务定期读取目标Cookie;
  3. 对比当前Cookie值与历史基准值,若发现内容变化则读取并处理消息;
  4. 更新基准值,完成一次跨页面通讯闭环。

需特别注意:Cookie的domainpath配置是轮询生效的前提——写入方与轮询方需配置一致的作用域(如根路径/、根域名example.com),否则轮询方无法读取目标Cookie,导致通讯失效。

2. 案例代码

2.1 Cookie 轮询完整实现

代码如下所示:

// 设置 Cookie
function setCookie(name, value, days = 1) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    const expires = "expires=" + date.toUTCString();
    document.cookie = name + "=" + encodeURIComponent(value) + ";" + expires + ";path=/";
    updateCookieDisplay();
}

// 获取 Cookie
function getCookie(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
    }
    return null;
}

// 删除 Cookie
function deleteCookie(name) {
    document.cookie = name + &#34;=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;&#34;;
    updateCookieDisplay();
}

// 发送消息(Cookie 方式)
function sendMessageByCookie(content) {
    // 确定通讯类型
    let communicationType = '';
    if (isChild) {
        communicationType = '子父通讯';
    } else {
        communicationType = '父子通讯';
    }
    
    const message = {
        id: Date.now(),
        content: content,
        sender: clientId,
        timestamp: Date.now(),
        method: 'cookie',
        communicationType: communicationType
    };
    
    const cookieValue = JSON.stringify(message);
    setCookie(COOKIE_NAME, cookieValue);
    addLog(`通过 Cookie 发送消息: ${content}`, '发送', communicationType);
}

image.png

3.2 总结

Cookie轮询是一种兼容性极强的跨页面通讯方案,无需依赖现代API,可在老旧浏览器中稳定运行。其核心优势是实现简单、配置灵活,适用于低频率消息同步场景(如登录状态、用户偏好设置)。使用时需重点关注Cookie作用域配置和轮询性能平衡,通过结构化消息设计和异常处理提升方案可靠性。

❌
❌