Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

jsdom

> 前端框架
Open source

A JavaScript implementation of various web standards, for use with Node.js

21.6K stars0 likes2 views
WebsiteGitHub

About

A JavaScript implementation of various web standards, for use with Node.js


jsdom

jsdom is a pure-JavaScript implementation of many web standards, notably the WHATWG DOM and HTML Standards, for use with Node.js. In general, the goal of the project is to emulate enough of a subset of a web browser to be useful for testing and scraping real-world web applications.

The latest versions of jsdom require newer Node.js versions; see the package.json "engines" field for details.

Basic usage

javascript
const jsdom = require("jsdom");
const { JSDOM } = jsdom;

To use jsdom, you will primarily use the JSDOM constructor, which is a named export of the jsdom main module. Pass the constructor a string. You will get back a JSDOM object, which has a number of useful properties, notably window:

javascript
const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`);
console.log(dom.window.document.querySelector("p").textContent); // "Hello world"

(Note that jsdom will parse the HTML you pass it just like a browser does, including implied <html>, <head>, and <body> tags.)

The resulting object is an instance of the JSDOM class, which contains a number of useful properties and methods besides window. In general, it can be used to act on the jsdom from the "outside," doing things that are not possible with the normal DOM APIs. For simple cases, where you don't need any of this functionality, we recommend a coding pattern like

javascript
const { window } = new JSDOM(`...`);
// or even
const { document } = (new JSDOM(`...`)).window;

Full documentation on everything you can do with the JSDOM class is below, in the section "JSDOM Object API".

Customizing jsdom

The JSDOM constructor accepts a second parameter which can be used to customize your jsdom in the following ways.

Simple options

javascript
const dom = new JSDOM(``, {
  url: "https://example.org/",
  referrer: "https://example.com/",
  contentType: "text/html",
  includeNodeLocations: true,
  storageQuota: 10000000
});
  • url sets the value returned by window.location, document.URL, and document.documentURI, and affects things like resolution of relative URLs within the document and the same-origin restrictions and referrer used while fetching subresources. It defaults to "about:blank".
  • referrer just affects the value read from document.referrer. It defaults to no referrer (which reflects as the empty string).
  • contentType affects the value read from document.contentType, as well as how the document is parsed: as HTML or as XML. Values that are not a HTML MIME type or an XML MIME type will throw. It defaults to "text/html". If a charset parameter is present, it can affect binary data processing.
  • includeNodeLocations preserves the location info produced by the HTML parser, allowing you to retrieve it with the nodeLocation() method (described below). It also ensures that line numbers reported in exception stack traces for code running inside <script> elements are correct. It defaults to false to give the best performance, and cannot be used with an XML content type since our XML parser does not support location info.
  • storageQuota is the maximum size in code units for the separate storage areas used by localStorage and sessionStorage. Attempts to store data larger than this limit will cause a DOMException to be thrown. By default, it is set to 5,000,000 code units per origin, as inspired by the HTML specification.

Note that both url and referrer are canonicalized before they're used, so e.g. if you pass in "https:example.com", jsdom will interpret that as if you had given "https://example.com/". If you pass an unparseable URL, the call will throw. (URLs are parsed and serialized according to the URL Standard.)

Executing scripts

jsdom's most powerful ability is that it can execute scripts inside the jsdom. These scripts can modify the content of the page and access all the web platform APIs jsdom implements.

However, this is also highly dangerous when dealing with untrusted content. The jsdom sandbox is not foolproof, and code running inside the DOM's <script>s can, if it tries hard enough, get access to the Node.js environment, and thus to your machine. As such, the ability to execute scripts embedded in the HTML is disabled by default:

javascript
const dom = new JSDOM(`<body>
  

  <script>document.getElementById("content").append(document.createElement("hr"));</script>
</body>`);

// The script will not be executed, by default:
console.log(dom.window.document.getElementById("content").children.length); // 0

To enable executing scripts inside the page, you can use the runScripts: "dangerously" option:

javascript
const dom = new JSDOM(`<body>
  

  <script>document.getElementById("content").append(document.createElement("hr"));</script>
</body>`, { runScripts: "dangerously" });

// The script will be executed and modify the DOM:
console.log(dom.window.document.getElementById("content").children.length); // 1

Again we emphasize to only use this when feeding jsdom code you know is safe. If you use it on arbitrary user-supplied code, or code from the Internet, you are effectively running untrusted Node.js code, and your machine could be compromised.

If you want to execute external scripts, included via <script src="">, you'll also need to ensure that they load them. To do this, add the option resources: "usable" as described below. (You'll likely also want to set the url option, for the reasons discussed there.)

Event handler attributes, like `

`, { runScripts: "outside-only" });

// run a script outside of JSDOM: dom.window.eval('document.getElementById("content").append(document.createElement("p"));');

console.log(dom.window.document.getElementById("content").children.length); // 1 console.log(dom.window.document.getElementsByTagName("hr").length); // 0 console.log(dom.window.document.getElementsByTagName("p").length); // 1

…

js const window = (new JSDOM(``, { pretendToBeVisual: true })).window;

window.requestAnimationFrame(timestamp => { console.log(timestamp > 0); });

…

js const { JSDOM, requestInterceptor } = require("jsdom");

const dom = new JSDOM(<script src="https://example.com/some-specific-script.js"></script>, { url: "https://example.com/", runScripts: "dangerously", resources: { userAgent: "Mellblomenator/9000", dispatcher: new ProxyAgent("http://127.0.0.1:9001"), interceptors: [ requestInterceptor((request, context) => { // Override the contents of this script to do something unusual. if (request.url === "https://example.com/some-specific-script.js") { return new Response("window.someGlobal = 5;", { headers: { "Content-Type": "application/javascript" } }); } // Return undefined to let the request proceed normally }) ] } });


The context object passed to the interceptor includes `element` (the DOM element that initiated the request, or `null` for requests that are not from DOM elements). For example:

```js
requestInterceptor((request, { element }) => {
  if (element) {
    console.log(`Element ${element.localName} is requesting ${request.url}`);
  }
  // Return undefined to let the request proceed normally
})

…

js
const virtualConsole = new jsdom.VirtualConsole();
const dom = new JSDOM(``, { virtualConsole });

Code like this will create a virtual console with no behavior. You can give it behavior by adding event listeners for all the possible console methods:

javascript
virtualConsole.on("error", () => { ... });
virtualConsole.on("warn", () => { ... });
virtualConsole.on("info", () => { ... });
virtualConsole.on("dir", () => { ... });
// ... etc. See https://console.spec.whatwg.org/#logging

(Note that it is probably best to set up these event listeners before calling new JSDOM(), since errors or console-invoking script might occur during parsing.)

If you simply want to redirect the virtual console output to another console, like the default Node.js one, you can do

javascript
virtualConsole.forwardTo(console);

…

js
// Do not send any jsdom errors to the Node.js console:
virtualConsole.forwardTo(console, { jsdomErrors: "none" });

// Send only certain jsdom errors to the Node.js console, ignoring others:
virtualConsole.forwardTo(console, { jsdomErrors: ["unhandled-exception", "not-implemented"]});

// Customize the handling of all jsdom errors:
virtualConsole.forwardTo(console, { jsdomErrors: "none" });
virtualConsole.on("jsdomError", err => {
  switch (err.type) {
    case "unhandled-exception": {
      // ... process ...
      break;
    }
    case "css-parsing": {
      // ... process in some other way ...
      break;
    }
    // ... etc. ...
  }
});

…

js
const cookieJar = new jsdom.CookieJar(store, options);
const dom = new JSDOM(``, { cookieJar });

…

js
const dom = new JSDOM(`<p>Hello</p>`, {
  beforeParse(window) {
    window.document.childNodes.length === 0;
    window.someCoolAPI = () => { /* ... */ };
  }
});

…

js
const dom = new JSDOM(`<!DOCTYPE html>hello`);

dom.serialize() === "<!DOCTYPE html><html><head></head><body>hello</body></html>";

// Contrast with:
dom.window.document.documentElement.outerHTML === "<html><head></head><body>hello</body></html>";

Getting the source location of a node with nodeLocation(node)

The nodeLocation() method will find where a DOM node is within the source document, returning the parse5 location info for the node:

javascript
const dom = new JSDOM(
  `<p>Hello
    
  </p>`,
  { includeNodeLocations: true }
);

const document = dom.window.document;
const bodyEl = document.body; // implicitly created
const pEl = document.querySelector("p");
const textNode = pEl.firstChild;
const imgEl = document.querySelector("img");

console.log(dom.nodeLocation(bodyEl));   // null; it's not in the source
console.log(dom.nodeLocation(pEl));      // { startOffset: 0, endOffset: 39, startTag: ..., endTag: ... }
console.log(dom.nodeLocation(textNode)); // { startOffset: 3, endOffset: 13 }
console.log(dom.nodeLocation(imgEl));    // { startOffset: 13, endOffset: 32 }

…

js
const { Script } = require("vm");

const dom = new JSDOM(``, { runScripts: "outside-only" });
const script = new Script(`
  if (!this.ran) {
    this.ran = 0;
  }

  ++this.ran;
`);

const vmContext = dom.getInternalVMContext();

script.runInContext(vmContext);
script.runInContext(vmContext);
script.runInContext(vmContext);

console.assert(dom.window.ran === 3);

…

js
const dom = new JSDOM();

dom.window.top === dom.window;
dom.window.location.href === "about:blank";

dom.reconfigure({ windowTop: myFakeTopForTesting, url: "https://example.com/" });

dom.window.top === myFakeTopForTesting;
dom.window.location.href === "https://example.com/";

…

js
JSDOM.fromURL("https://example.com/", options).then(dom => {
  console.log(dom.serialize());
});

…

js
JSDOM.fromFile("stuff.html", options).then(dom => {
  console.log(dom.serialize());
});

…

js
const frag = JSDOM.fragment(`<p>Hello</p><p><strong>Hi!</strong>`);

frag.childNodes.length === 2;
frag.querySelector("strong").textContent === "Hi!";
// etc.

…

js
const frag = JSDOM.fragment(`<p>Hello</p>`);
console.log(frag.firstChild.outerHTML); // logs "<p>Hello</p>"

…

js
// On the Node.js side:
const window = (new JSDOM(...)).window;
window.onModulesLoaded = () => {
  console.log("ready to roll!");
};
xml

<script>
requirejs(["entry-module"], () => {
  wi

Issues· 307 open

View all issuesOpen on GitHub
  • #4167

    Implement CookieStore API

    Updated Sep 30, 2026
  • #4330

    getComputedStyle inheritance walk is O(2^ancestor-depth) for a custom property set to inherit/unset

    Updated Sep 22, 2026
  • #3050

    Including width and height in <img> results in 2 requests

    Updated Sep 22, 2026
  • #4340

    Quiet MutationObservers retain dead weak-reference bookkeeping

    memoryUpdated Sep 21, 2026
  • #4339

    The CSS parser retains the last stylesheet window through its error callback

    memoryUpdated Sep 17, 2026
  • #4338

    The cached default stylesheet retains the first style-computation window

    memoryUpdated Sep 17, 2026
  • #4337

    Canceled pending interceptors retain closed windows

    memoryUpdated Sep 17, 2026
  • #4336

    Distinct selectors grow an unbounded cache for each live document

    memoryUpdated Sep 17, 2026
  • #3291

    jsdom get call is interpreted as image

    real world problemUpdated Sep 17, 2026
  • #1737

    window DOM classes should be instanceof window.Function

    Updated Sep 17, 2026

> Tags

JavaScriptdom-apishtmljavascriptjsdom

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 1, 2026
Category前端框架
PricingOpen source

> Related tools

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架