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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
20 lines
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 runtime

What to watch for

  • This is browser-side code — document will 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

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.