$ npm install jsdom
If this gives you trouble with errors about installing Contextify, especially on Windows, see below.
see: mailing list
jsdom.env is an API that allows you to throw a bunch of stuff at it, and it will generally do the right thing.
You can use it with a URL
// Count all of the links from the Node.js build pagevar jsdom = require"jsdom";jsdomenv""""console.log"there have been" window$"a"length "nodejs releases!";;
or with raw HTML
// Run some jQuery on a html fragmentvar jsdom = require"jsdom";jsdomenv'<p><a class="the-link" href="">jsdom!</a></p>'""console.log"contents of a.the-link:" window$"a.the-link"text;;
or with a configuration object
// Print all of the news items on Hacker Newsvar jsdom = require"jsdom";jsdomenvurl: ""scripts: ""var $ = window$;console.log"HN Links";$"td.title:not(:last) a"eachconsole.log" -" $thistext;;;
// Print all of the news items on Hacker Newsvar jsdom = require"jsdom";var fs = require"fs";var jquery = fsreadFileSync"./jquery.js" "utf-8";jsdomenvurl: ""src: jqueryvar $ = window$;console.log"HN Links";$"td.title:not(:last) a"eachconsole.log" -" $thistext;;;
The do-what-I-mean API is used like so:
jsdomenvstring scripts config callback;
string: may be a URL, file name, or HTML fragment
scripts: a string or array of strings, containing file names or URLs that will be inserted as
config: see below
callback: takes two arguments
null, if nothing goes wrong, or an array of errors
window: a brand new
window, if there were no loading errors
jsdomenvhtml// free memory associated with the windowwindowclose;;
If you would like to specify a configuration object only:
config.html: a HTML fragment
config.file: a file which jsdom will load HTML from; the resulting window's
location.hrefwill be a
config.url: sets the resulting window's
config.fileare not provided, jsdom will load HTML from this URL.
config.jar: a custom cookie jar, if desired; see mikeal/request documentation.
"xml". The default is
"auto", which uses HTML behavior unless
config.urlresponds with an XML
config.filecontains a filename ending in
.xhtml. Setting to
"xml"will attempt to parse the document as an XHTML document. (jsdom is currently only OK at doing that.)
referrer: the new document will have this referrer.
cookie: manually set a cookie value, e.g.
'key=value; expires=Wed, Sep 21 2011 12:00:00 GMT; path=/'.
cookieDomain: a cookie domain for the manually set cookie; defaults to
config.headers: an object giving any headers that will be used while loading the HTML from
config.url, if applicable
config.features: see Flexibility section below. Note: the default feature set for
config.resourceLoader: a function that intercepts subresource requests and allows you to re-route them, modify, or outright replace them with your own content. More below.
config.created: see below.
Note that at least one of the callbacks (
created) is required, as is one of
If you just want to load the document and execute it, the
done callback shown above is the simplest. If anything goes wrong, either while loading the document and creating the window, or while executing any
<script>s, the problem will show up in the
errors array passed as the first argument.
However, if you want more control over or insight into the initialization lifecycle, you'll want to use the
created callback is called as soon as the window is created, or if that process fails. You may access all
window properties here; however,
window.document is not ready for use yet, as the HTML has not been parsed.
The primary use-case for
created is to modify the window object (e.g. add new functions on built-in prototypes) before any scripts execute.
You can also set an event handler for
'load' or other events on the window if you wish. But the
loaded callback, below, can be more useful, since it includes script errors.
error argument is non-
null, it will contain whatever loading error caused the window creation to fail; in that case
window will not be passed.
loaded callback is called along with the window's
'load' event. This means it will only be called if creation succeeds without error. Note that by the time it has called, any external resources will have been downloaded, and any
<script>s will have finished executing.
errors is non-
window will still be passed, however.
Now that you know about
loaded, you can see that
done is essentially both of them smashed together:
<script>s cause errors, then
errorswill be null, and
windowwill be usable.
errorswill be an array containing those errors, but
windowwill still be usable.
errorswill be an array containing the creation error, and
windowwill not be passed.
If you used jsdom before v1.0.0, it only had a
done callback, and it was kind of buggy, sometimes behaving one way, and sometimes another. Due to some excellent work by @Sebmaster in #792, we fixed it up into the above lifecycle. For more information on the migration, see the wiki.
If you load scripts asynchronously, e.g. with a module loader like RequireJS, none of the above hooks will really give you what you want. There's nothing, either in jsdom or in browsers, to say "notify me after all asynchronous loads have completed." The solution is to use the mechanisms of the framework you are using to notify about this finishing up. E.g., with RequireJS, you could do
// On the Node side:var window = jsdomjsdomparentWindow;console.log"ready to roll!";;
<!-- Inside the HTML you supply to jsdom -->
jsdom.jQueryify, or modify the defaults passed to
jsdom.jsdom method does less things automatically; it takes in only HTML source, and does not let you to separately supply script that it will inject and execute. It just gives you back a
document object, with usable
document.parentWindow, and starts asynchronously executing any
<script>s included in the HTML source. You can listen for the
'load' event to wait until scripts are done loading and executing, just like you would in a normal HTML page.
Usage of the API generally looks like this:
var jsdom = require"jsdom"jsdom;var doc = jsdommarkup options;var window = docparentWindow;
markup is a HTML document to be parsed. You can also pass
undefined to get the basic document, equivalent to what a browser will give if you open up an empty
options: see the explanation of the
config object above.
One of the goals of jsdom is to be as minimal and light as possible. This section details how someone can change the behavior of
Documents before they are created. These features are baked into the
DOMImplementation that every
Document has, and may be tweaked in two ways:
Document, by overriding the configuration:
var jsdom = require"jsdom"jsdom;var doc = jsdom"<html><body></body></html>"features:FetchExternalResources : "img";
Do note, that this will only affect the document that is currently being created. All other documents will use the defaults specified below (see: Default Features).
require"jsdom"defaultDocumentFeatures =FetchExternalResources: "script"ProcessExternalResources: false;
Default features are extremely important for jsdom as they lower the configuration requirement and present developers a set of consistent default behaviors. The following sections detail the available features, their defaults, and the values that jsdom uses.
["script", "img", "css", "frame", "iframe", "link"]or
Enables/disables fetching files over the file system/HTTP
/url to be skipped/or
Filters resource downloading and processing to disallow those matching the given regular expression
jsdom lets you intercept subresource requests using
config.resourceLoader expects a function which is called for each subresource request with the following arguments:
url: a parsed URL object.
cookie: the content of the HTTP cookie header (
key=valuepairs separated by semicolons).
cookieDomain: the cookie domain as set in
config, defaults to
baseUrl: the base URL used to resolve relative URLs.
defaultFetch(callback): a convenience method to fetch the resource online.
callback: a function to be called with two arguments
null, if nothing goes wrong, or an
body: a string representing the body of the resource.
For example, fetching all JS files from a different directory and running them in strict mode:
var jsdom = require"jsdom";jsdomenvurl: ""var pathname = resourceurlpathname;if /\.js$/testpathnameresourceurlpathname = pathnamereplace"/js/" "/js/raw/";resourcedefaultFetchif err return callbackerr;callbacknull '"use strict";\n' + body;;elseresourcedefaultFetchcallback;features:FetchExternalResources: "script"ProcessExternalResources: "script"SkipExternalResources: false;
jsdom includes support for using the canvas package to extend any
<canvas> elements with the canvas API. To make this work, you need to include canvas as a dependency in your project, as a peer of jsdom. If jsdom can find the canvas package, it will use it, but if it's not present, then
<canvas> elements will behave like
var jsdom = require"jsdom"jsdom;var document = jsdom"hello world";var window = documentparentWindow;console.logwindowdocumentdocumentElementouterHTML;// output: "<html><head></head><body>hello world</body></html>"console.logwindowinnerWidth;// output: 1024console.logtypeof windowdocumentgetElementsByClassName;// outputs: function
var jsdom = require"jsdom";var window = jsdomjsdomparentWindow;jsdomjQueryifywindow ""window$"body"append'<div class="testing">Hello World, It works</div>';console.logwindow$".testing"text;;
var jsdom = require"jsdom"jsdom;var window = jsdomparentWindow;window__myObject = foo: "bar" ;var scriptEl = windowdocumentcreateElement"script";scriptElsrc = "anotherScript.js";windowdocumentbodyappendChildscriptEl;// anotherScript.js will have the ability to read `window.__myObject`, even// though it originated in Node!
var jsdom = require"jsdom"jsdom;var serializeDocument = require"jsdom"serializeDocument;var doc = jsdom"<!DOCTYPE html>hello";serializeDocumentdoc === "<!DOCTYPE html><html><head></head><body>hello</body></html>";docdocumentElementouterHTML === "<html><head></head><body>hello</body></html>";
var jsdom = require"jsdom";var window = jsdomjsdomparentWindow;jsdomgetVirtualConsolewindowsendToconsole;
var jsdom = require"jsdom";var window = jsdomjsdomparentWindow;var virtualConsole = jsdomgetVirtualConsolewindow;virtualConsoleon"log"console.log"console.log called ->" message;;
Our mission is to get something very close to a headless browser, with emphasis more on the DOM/HTML side of things than the CSS side. As such, our primary goals are supporting The DOM Standard and The HTML Standard. We only support some subset of these so far; in particular we have the subset covered by the outdated DOM 2 spec family down pretty well. We're slowly including more and more from the modern DOM and HTML specs, including some
querySelector(All), attribute semantics, the history and URL APIs, and the HTML parsing algorithm.
We also support some subset of the CSSOM, largely via @chad3814's excellent cssstyle package. In general we want to make webpages run headlessly as best we can, and if there are other specs we should be incorporating, let us know.
Contextify is a dependency of jsdom, used for running
Getting C++ compiled within npm's installation system can be tricky, especially for Windows users. Thus, one of the most common problems with jsdom is trying to use it without the proper compilation tools installed. Here's what you need to compile Contextify, and thus to install jsdom:
The latest version of Node.js for Windows
A copy of Python 2.7, installed in the default location of
Set your system environment variable GYP_MSVS_VERSION like so (assuming you have Visual Studio 2013 installed):
setx GYP_MSVS_VERSION 2013
Restart your command prompt window to ensure required path variables are present.
There are some slight modifications to this that can work; for example other Visual Studio versions often work too. But it's tricky, so start with the basics!
You'll need various build tools installed, like
make, Python 2.7, and a compiler toolchain. How to install these will be specific to your distro, if you don't already have them.