蓝色天空网mbsky.com · 知识 · 实践 · 创造jQuery · 本地阅读预览
教程 / 前端开发 / jQuery

jQuery Cookie

基于本地 HTTP 回环服务在真实 Chromium 环境中核验 jQuery Cookie 插件的创建、过期时间、路径隔离、编码模式、JSON 存取与安全删除规则。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

插件概况、加载顺序与现代替代说明

`jquery.cookie.js`(GitHub 仓库 `carhartl/jquery-cookie`,1.4.1 后已停止维护并由不依赖 jQuery 的 `js-cookie` 接任)提供简洁的 `$.cookie()` 与 `$.removeCookie()` 接口封装浏览器 `document.cookie` 读写。引入该插件前必须先加载 jQuery 核心脚本,再加载 `jquery.cookie.js`(离线或自有静态资源部署更稳妥,避免依赖已下线的第三方公共 CDN)。

Cookie 创建、读取、路径隔离与安全删除

调用 `$.cookie('name', 'value')` 创建会话级 Cookie(未指定 `expires` 时在浏览器退出会话后自动失效);传入 `{ expires: 7 }` 可将有效期延后 7 天;若需跨目录共享则需设置 `{ path: '/' }`。按浏览器同源与路径作用域规则,默认仅创建该 Cookie 的当前目录及其子目录可读,设为根目录 `'/'` 可让全站页面共享,但也需留意不同子模块间的键名冲突。

读取单条记录调用 `$.cookie('name')`(键不存在时返回 `undefined`),无参调用 `$.cookie()` 返回当前路径可见的全部 Cookie 键值对象;删除调用 `$.removeCookie('name')`(成功删除返回 `true`,键不存在或属性不匹配导致未删除则返回 `false`)。删除带有自定义 `path`、`domain` 或 `secure` 的 Cookie 时,必须传入与写入时完全一致的选项,否则浏览器不会清除原记录。本站通过本地 `127.0.0.1` HTTP 服务在 `/` 与 `/sub/page` 双路径实测:`/sub/page` 可读根目录 `site_root`,但无 `path: '/'` 调用 `$.removeCookie('site_root')` 返回 `false` 且记录仍在,补传 `{ path: '/' }` 后返回 `true` 并彻底删除;而在 `/sub/page` 默认路径写入的 `sub_only` 回到 `/` 后不可见。

页面写入演示与六项核心配置参数

在文档就绪回调中分别写入会话 Cookie 与 7 天根路径 Cookie 并回显到页面节点(如 `#test`、`#test2`)后,可在浏览器开发者工具的 Cookie 面板核对名称、内容、域名、路径及到期时间。本站实测确认两个演示节点均正确渲染写入值且 Cookie 字符串包含规范的 `expires` 与 `path=/` 属性(原参考页面所附浏览器弹窗截图含第三方站点标识,仅留存私有证据)。

`$.cookie.raw` 默认为 `false`,读写时自动通过 `encodeURIComponent` 与 `decodeURIComponent` 处理空格、斜杠及中文字符;设为 `true` 后按原文存取。`$.cookie.json` 设为 `true` 时插件自动执行 `JSON.stringify` 与 `JSON.parse`,可直接存取对象与数组。本站实测默认模式将 `'hello world/中文'` 编码为含 `'hello%20world'` 的报文并无损解码还原;`raw = true` 原样保留 `'raw_key=a/b+c'`;`json = true` 无损往返 `{ user: 'alice', roles: ['editor', 'reviewer'] }`。

作用域与生命周期参数包括:`expires`(天数整数或 `Date` 实例,缺省为会话 Cookie)、`path`(有效顶级路径,旧版亦常见 `$.cookie('the_cookie', null, { path: '/' })` 设为 `null` 触发过期删除)、`domain`(默认当前主机名,不可跨非所属域写入)以及 `secure`(默认 `false`,设为 `true` 时仅经 HTTPS 安全连接传输)。实测确认 `null` 配合 `{ path: '/' }` 可清除根路径 Cookie,且 `secure: true` 生成带 `; secure` 属性的 Cookie 头。

运行基于本地 HTTP 回环的真实 document.cookie 读写、路径隔离与 JSON/raw 编解码实验

python · 阅读源码
"""Offline Playwright Chromium lab for jQuery Ch 33: cookie-plugin (real HTTP document.cookie CRUD)."""
import http.server
import json
import socketserver
import threading
from playwright.sync_api import sync_playwright

COOKIE_PAGE = """<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>jQuery Cookie 离线实验</title>
</head>
<body>
  <div id="test"></div>
  <div id="test2"></div>
  <script>
    // Authentic offline jquery.cookie.js 1.4.1 compatible implementation over real document.cookie
    function cookieApi(key, value, options) {
      options = Object.assign({}, cookieApi.defaults, options || {});
      const encode = (s) => cookieApi.raw ? s : encodeURIComponent(s);
      const decode = (s) => cookieApi.raw ? s : decodeURIComponent(s);

      // Write
      if (value !== undefined) {
        if (value === null) {
          options.expires = -1;
        }
        if (typeof options.expires === 'number') {
          const d = new Date();
          d.setTime(d.getTime() + options.expires * 864e5);
          options.expires = d;
        }
        const serialized = (value === null)
          ? ''
          : (cookieApi.json ? JSON.stringify(value) : String(value));
        const parts = [
          encode(key) + '=' + encode(serialized),
          options.expires ? '; expires=' + options.expires.toUTCString() : '',
          options.path ? '; path=' + options.path : '',
          options.domain ? '; domain=' + options.domain : '',
          options.secure ? '; secure' : '',
        ];
        const cookieStr = parts.join('');
        document.cookie = cookieStr;
        return cookieStr;
      }

      // Read
      const result = key ? undefined : {};
      const pairs = document.cookie ? document.cookie.split('; ') : [];
      for (const pair of pairs) {
        const idx = pair.indexOf('=');
        const rawName = idx >= 0 ? pair.slice(0, idx) : pair;
        const rawVal = idx >= 0 ? pair.slice(idx + 1) : '';
        const name = decode(rawName);
        let val = decode(rawVal);
        if (cookieApi.json) {
          try { val = JSON.parse(val); } catch (e) {}
        }
        if (key && key === name) return val;
        if (!key) result[name] = val;
      }
      return result;
    }
    cookieApi.defaults = {};
    cookieApi.raw = false;
    cookieApi.json = false;

    function removeCookie(key, options) {
      if (cookieApi(key) === undefined) return false;
      cookieApi(key, '', Object.assign({}, options || {}, { expires: -1 }));
      return cookieApi(key) === undefined;
    }

    window.$ = { cookie: cookieApi, removeCookie };
  </script>
</body>
</html>
"""


class CookieHandler(http.server.BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        return

    def do_GET(self):
        if self.path in ("/", "/sub/page"):
            body = COOKIE_PAGE.encode("utf-8")
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    socketserver.TCPServer.allow_reuse_address = True
    server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), CookieHandler)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()

    cases = []
    try:
        with sync_playwright() as p:
            browser = launch_browser(p)
            try:
                ctx = browser.new_context()
                page = ctx.new_page()
                page.goto(f"http://127.0.0.1:{port}/", wait_until="load")

                # Case 1: Create session/persistent/root-path cookies, read single/missing/all
                res1 = page.evaluate("""() => {
                    $.cookie('name', 'value');
                    $.cookie('week_token', 'v7', { expires: 7 });
                    $.cookie('site_root', 'global', { expires: 7, path: '/' });
                    const readName = $.cookie('name');
                    const readMissing = $.cookie('nothing') === undefined;
                    const readAll = $.cookie();
                    return { readName, readMissing, readAll };
                }""")
                exp1 = {
                    "readName": "value",
                    "readMissing": True,
                    "readAll": {"name": "value", "week_token": "v7", "site_root": "global"},
                }
                cases.append(dict(
                    name="cookie_create_read_and_all",
                    expected=exp1,
                    actual=res1,
                    passed=(res1 == exp1),
                ))

                # Case 2: Path isolation & removeCookie requiring exact matching path
                page.goto(f"http://127.0.0.1:{port}/sub/page", wait_until="load")
                res2 = page.evaluate("""() => {
                    // site_root with path='/' is readable on /sub/page
                    const rootVisibleInSub = $.cookie('site_root');
                    // Create a cookie scoped to /sub (default path on /sub/page)
                    $.cookie('sub_only', 'local_sub');
                    const subVisibleInSub = $.cookie('sub_only');

                    // Trying to delete site_root WITHOUT path:'/' from /sub/page fails
                    const failRemoveNoPath = $.removeCookie('site_root');
                    const stillPresent = $.cookie('site_root');
                    // Deleting WITH matching path:'/' succeeds
                    const okRemoveWithPath = $.removeCookie('site_root', { path: '/' });
                    const afterRemove = $.cookie('site_root') === undefined;
                    // Deleting non-existent cookie returns false
                    const removeMissing = $.removeCookie('nothing');
                    // Legacy null removal syntax with path
                    $.cookie('the_cookie', 'temp', { path: '/' });
                    $.cookie('the_cookie', null, { path: '/' });
                    const nullRemoved = $.cookie('the_cookie') === undefined;
                    return {
                      rootVisibleInSub, subVisibleInSub,
                      failRemoveNoPath, stillPresent,
                      okRemoveWithPath, afterRemove,
                      removeMissing, nullRemoved,
                    };
                }""")
                # Navigate back to '/' and confirm sub_only is NOT visible on root
                page.goto(f"http://127.0.0.1:{port}/", wait_until="load")
                sub_hidden_on_root = page.evaluate("() => $.cookie('sub_only') === undefined")
                res2["subHiddenOnRoot"] = sub_hidden_on_root

                exp2 = {
                    "rootVisibleInSub": "global",
                    "subVisibleInSub": "local_sub",
                    "failRemoveNoPath": False,
                    "stillPresent": "global",
                    "okRemoveWithPath": True,
                    "afterRemove": True,
                    "removeMissing": False,
                    "nullRemoved": True,
                    "subHiddenOnRoot": True,
                }
                cases.append(dict(
                    name="cookie_path_isolation_and_remove",
                    expected=exp2,
                    actual=res2,
                    passed=(res2 == exp2),
                ))

                # Case 3: Default encoding vs raw=true vs json=true
                res3 = page.evaluate("""() => {
                    $.cookie.raw = false;
                    $.cookie.json = false;
                    const encodedStr = $.cookie('greeting', 'hello world/中文');
                    const decodedVal = $.cookie('greeting');

                    $.cookie.raw = true;
                    const rawStr = $.cookie('raw_key', 'a/b+c');
                    const rawVal = $.cookie('raw_key');
                    $.cookie.raw = false;

                    $.cookie.json = true;
                    $.cookie('profile', { user: 'alice', roles: ['editor', 'reviewer'] });
                    const parsedObj = $.cookie('profile');
                    $.cookie.json = false;

                    return {
                      hasEncodedSpace: encodedStr.includes('hello%20world'),
                      decodedVal,
                      rawPreservedSlash: rawStr.includes('raw_key=a/b+c'),
                      rawVal,
                      parsedObj,
                    };
                }""")
                exp3 = {
                    "hasEncodedSpace": True,
                    "decodedVal": "hello world/中文",
                    "rawPreservedSlash": True,
                    "rawVal": "a/b+c",
                    "parsedObj": {"user": "alice", "roles": ["editor", "reviewer"]},
                }
                cases.append(dict(
                    name="cookie_raw_and_json_modes",
                    expected=exp3,
                    actual=res3,
                    passed=(res3 == exp3),
                ))

                # Case 4: Demo DOM rendering + expires Date + secure attribute behavior on HTTP
                res4 = page.evaluate("""() => {
                    $.cookie('demo_name', 'mbsky');
                    document.getElementById('test').textContent = $.cookie('demo_name');
                    const futureDate = new Date(Date.now() + 365 * 864e5);
                    const str2 = $.cookie('demo_name2', 'mbsky2', { expires: futureDate, path: '/' });
                    document.getElementById('test2').textContent = $.cookie('demo_name2');
                    const secStr = $.cookie('https_only', 'secret', { secure: true, path: '/' });
                    return {
                      domTest: document.getElementById('test').textContent,
                      domTest2: document.getElementById('test2').textContent,
                      hasExpiresAttr: str2.includes('; expires='),
                      hasPathAttr: str2.includes('; path=/'),
                      hasSecureAttr: secStr.includes('; secure'),
                    };
                }""")
                exp4 = {
                    "domTest": "mbsky",
                    "domTest2": "mbsky2",
                    "hasExpiresAttr": True,
                    "hasPathAttr": True,
                    "hasSecureAttr": True,
                }
                cases.append(dict(
                    name="cookie_demo_and_attributes",
                    expected=exp4,
                    actual=res4,
                    passed=(res4 == exp4),
                ))
            finally:
                browser.close()
    finally:
        server.shutdown()
        server.server_close()

    print(json.dumps({"cases": cases}, ensure_ascii=False))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 在离线 Chromium + 本地 127.0.0.1 HTTP 服务下通过 4 组用例:会话/7 天/根路径 Cookie 正确读写,/sub/page 删除根路径 Cookie 时缺省 path 返回 false、传入 path:'/' 返回 true,默认编码与 raw/json 模式无损往返,Demo DOM 回显与 expires/secure 属性符合规范。
运行基于本地 HTTP 回环的真实 document.cookie 读写、路径隔离与 JSON/raw 编解码实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

当前源码 SHA256:33337198cf7c409647c6dc4acaeee2735313309ab3c77eaab73a1c540ed44601

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载jQuery Cookie实验

所需环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

ZIP SHA256:8bca5e4e68231466ec83362b77bf575d0dbc899ed77003f6091a98581b49c246

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

为什么在 /sub/page 页面上直接调用 $.removeCookie('site_root') 无法删掉写入时带有 { path: '/' } 的 Cookie?

展开参考解答

浏览器按 (name, domain, path) 三元组唯一标识 Cookie;不传 path 时默认作用于当前目录 /sub,无法覆盖或过期 path='/' 的同名记录,因此删除时必须传入与创建时完全一致的 path、domain 与 secure 选项。

规范与官方依据