示例工程 22-security-service-worker
22-security-service-worker/02-xss/main.test.mjs
该示例需要 localStorage / IndexedDB / Service Worker,请用「新窗口打开」获得完整能力。
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { escapeHtml, setText, run } from './main.js';
test('escapeHtml 转义五个关键字符', () => {
assert.equal(escapeHtml(`<&>"'`), '<&>"'');
});
test('escapeHtml 不重复转义已经转义的实体', () => {
assert.equal(escapeHtml('<'), '&lt;');
});
test('非字符串输入先转成字符串', () => {
assert.equal(escapeHtml(42), '42');
assert.equal(escapeHtml(null), 'null');
});
test('setText 写入纯文本并返回读回值', () => {
const el = {};
assert.equal(setText(el, '<b>x</b>'), '<b>x</b>');
assert.equal(el.textContent, '<b>x</b>');
});
test('Node 里调用 run 给出环境错误', () => {
assert.throws(() => run(() => {}), /需要浏览器环境/);
});