CodeSampleX

샘플

happy-dom 20.11.2: Initialize Happy DOM with options and populate markup via document.write or window.DOMParser rather than passing HTML strings to new Window or invoking standalone DOMParser

검증된 샘플 — npm happy-dom 20.11.2: Initialize Happy DOM with options and populate markup via document.write or window.DOMParser rather than passing HTML strings…

sha256:53aeae586fae7f02414a22588d189556a779055a4c627064ec6114aee07367ef

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 node linux x64 node node npm

검증 실행 환경

환경 컨트랙트 단계 실행일
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-16
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

케이스

HOW
목표
Initialize Happy DOM with options and populate markup via document.write or window.DOMParser rather than passing HTML strings to new Window or invoking standalone DOMParser
패키지
심벌
  • Window
  • DOMParser
환경
node
생성일
2026-08-16T16:45:38Z

컨트랙트

  1. new Window(html) ignores string arguments because the constructor expects an options object, leaving document.body.innerHTML empty and getElementById returning null.
  2. new DOMParser() imported standalone from happy-dom throws TypeError on parseFromString due to missing Window context binding.
  3. window.document.write(html) on an existing Window instance parses the HTML string into the active document.
  4. new window.DOMParser() bound to a Window instance successfully parses HTML into a new HTMLDocument.

파일

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

소스 아티팩트 내려받기 (tar.gz)

소스

NOTES.md
# happy-dom Window Instantiation and HTML Parsing

## Prior Search Results

A search for known solutions for `happy-dom` returned three unrelated samples:
- `sha256:e949d296b4b86f64c795f4aaf4915e41f0e6d78206d3732bfffc80877456b1a3` (Vitest 4 test environment globals and docblock precedence)
- `sha256:ffbf1189d6c67b17effd53b4f30bb520e3a01b2c792450fda6198ef4c832f34e` (React 19 server metadata hoisting)
- `sha256:82cb4df6ef197197d50a5f2da59ac8c68181ad3387e06b4a023e6aaac0ed58a9` (yaml v2 boolean parsing)

None covered DOM instantiation or HTML parsing entrypoint traps in `happy-dom`.

## Failure Modes

Passing an HTML markup string to `new Window(html)` fails silently with an empty `document.body.innerHTML` and `null` element queries, while calling `parseFromString()` on a standalone `new DOMParser()` fails loudly with `TypeError: Cannot read properties of undefined (reading 'HTMLDocument')`.
csx.json
{"case":{"believed":"Passing an HTML string to new Window(html) initializes the document markup, or instantiating new DOMParser() parses HTML strings into a DOM tree.","caseId":"case:sha256:a236542ae77b522b60ed6a2472615aaa2ef3c997c99af200491e2d392bcd8aeb","contract":["new Window(html) ignores string arguments because the constructor expects an options object, leaving document.body.innerHTML empty and getElementById returning null.","new DOMParser() imported standalone from happy-dom throws TypeError on parseFromString due to missing Window context binding.","window.document.write(html) on an existing Window instance parses the HTML string into the active document.","new window.DOMParser() bound to a Window instance successfully parses HTML into a new HTMLDocument."],"goal":"Initialize Happy DOM with options and populate markup via document.write or window.DOMParser rather than passing HTML strings to new Window or invoking standalone DOMParser","kind":"HOW","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["Window","DOMParser"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["Window","DOMParser"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-happy-dom-api",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-happy-dom-api",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "happy-dom": "^20.11.2"
      }
    },
    "node_modules/@types/node": {
      "version": "26.2.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
      "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/whatwg-mimetype": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
      "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
      "license": "MIT"
    },
    "node_modules/@types/ws": {
      "version": "8.18.1",
      "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
      "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      }
    },
    "node_modules/buffer-image-size": {
      "version": "0.6.4",
      "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
      "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      },
      "engines": {
        "node": ">=4.0"
      }
    },
    "node_modules/entities": {
      "version": "7.0.1",
      "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
      "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=0.12"
      },
      "funding": {
        "url": "https://github.com/fb55/entities?sponsor=1"
      }
    },
    "node_modules/happy-dom": {
      "version": "20.11.2",
      "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz",
      "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==",
      "license": "MIT",
      "dependencies": {
        "@types/node": ">=20.0.0",
        "@types/whatwg-mimetype": "^3.0.2",
        "@types/ws": "^8.18.1",
        "buffer-image-size": "^0.6.4",
        "entities": "^7.0.1",
        "whatwg-mimetype": "^3.0.0",
        "ws": "^8.21.0"
      },
      "engines": {
        "node": ">=20.0.0"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    },
    "node_modules/whatwg-mimetype": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
      "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "npm-happy-dom-api",
  "version": "1.0.0",
  "type": "module",
  "dependencies": {
    "happy-dom": "20.11.2"
  }
}
test/contract.mjs
import { Window, DOMParser } from 'happy-dom';
import assert from 'node:assert/strict';

// Trap 1: Callers passing an HTML string to new Window(html) expecting the document to be populated.
// Window constructor only takes an options object ({ url, width, height, console, settings });
// string arguments are ignored and the document body remains empty.
const html = '<div id="app"><span>Hello World</span></div>';
const windowInstance = new Window(html);

assert.strictEqual(
  windowInstance.document.body.innerHTML,
  '',
  'new Window(html) does not populate document body because string argument is ignored as options'
);
assert.strictEqual(
  windowInstance.document.getElementById('app'),
  null,
  'getElementById returns null when HTML was passed as a string to new Window'
);

// Trap 2: Callers importing DOMParser from top-level package and instantiating standalone.
// DOMParser requires an internal Window binding; standalone instances lack this[PropertySymbol.window]
// and throw a TypeError when accessing undefined.HTMLDocument.
const standaloneParser = new DOMParser();
assert.throws(
  () => standaloneParser.parseFromString(html, 'text/html'),
  {
    name: 'TypeError',
    message: "Cannot read properties of undefined (reading 'HTMLDocument')"
  },
  'new DOMParser() standalone throws TypeError when parsing without a bound Window context'
);

// Correct approach 1: Populate an existing Window using document.write(html)
const populatedWindow = new Window();
populatedWindow.document.write(html);

assert.strictEqual(
  populatedWindow.document.body.innerHTML,
  html,
  'window.document.write parses and populates HTML into the document body'
);
assert.strictEqual(
  populatedWindow.document.getElementById('app')?.textContent,
  'Hello World',
  'Elements are accessible in DOM tree after document.write'
);

// Correct approach 2: Use DOMParser instantiated from an active Window instance
const boundParser = new populatedWindow.DOMParser();
const parsedDocument = boundParser.parseFromString(html, 'text/html');

assert.strictEqual(
  parsedDocument.body.innerHTML,
  html,
  'new window.DOMParser() successfully parses HTML string into a separate HTMLDocument'
);
assert.strictEqual(
  parsedDocument.getElementById('app')?.textContent,
  'Hello World',
  'Elements are queryable from DOMParser-created document'
);

오리진 시더

csx-seed