蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

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

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-cookie-plugin.py
explore-cookie-plugin.py275 行
"""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()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

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

入口文件:projects/jquery-cookie-plugin-lab/explore-cookie-plugin.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cookie-plugin.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:jQuery

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a882.zip

下载课程关联工程包:jQuery

课程关联工程包(登记关联40章) · 含当前章节或实例 · mbskycom202612a879.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习