Template Markup Parses Without Scripts
Parse untrusted markup through a programmatic template: scripts never run, event-handler attributes stay inert, and content.cloneNode yields a disjoint tree.
Code
if (typeof document === 'undefined') {
console.log('DOM unavailable in this runtime');
} else {
// 程序化 template:innerHTML 只做解析,不属于渲染树
const tpl = document.createElement('template');
tpl.innerHTML = '<ul><li data-id="a">first</li><li data-id="b">second</li></ul>';
// 解析结果查询照常:script 永不执行,onerror 属性只是普通属性
const sneaky = document.createElement('template');
sneaky.innerHTML = '<img src=x onerror="steal()">';
const img = sneaky.content.firstElementChild;
console.log('attribute kept inert:', img.hasAttribute('onerror'), typeof img.onerror === 'function');
// cloneNode(true) 得到互不相干的树:改副本不动原件
const original = tpl.content.firstElementChild;
const copy = tpl.content.cloneNode(true).firstElementChild;
copy.querySelector('li').textContent = 'first (copy)';
console.log('original intact:', original.querySelector('li').textContent);
console.log('disjoint nodes :', original.querySelector('li') !== copy.querySelector('li'));
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
DOM unavailable in this runtimeWhat to watch for
- This is browser-side code —
documentwill not resolve in Node.
Applying it
Expect labeled output — DOM unavailable in this runtime — when the file runs.
Output is labeled for readability — expect lines prefixed with DOM unavailable in this runtime.
Statements that matter
tpl.innerHTML = '<ul><li data-id="a">first</li><li data-id="b">second</li></ul>';
const copy = tpl.content.cloneNode(true).firstElementChild;
copy.querySelector('li').textContent = 'first (copy)';
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Does Template Markup Parses Without Scripts run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.