jsdom
A JavaScript implementation of the WHATWG DOM and HTML standards.
Install
$ npm install jsdom
If this gives you trouble with errors about installing Contextify, especially on Windows, see below.
Human contact
see: mailing list
jsdom.env
Easymode: 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 = ; jsdom;
or with raw HTML
// Run some jQuery on a html fragmentvar jsdom = ; jsdom;
or with a configuration object
// Print all of the news items on Hacker Newsvar jsdom = ; jsdom;
or with raw JavaScript source
// Print all of the news items on Hacker Newsvar jsdom = ;var fs = ;var jquery = fs; jsdom;
How it works
The do-what-I-mean API is used like so:
jsdom;
string
: may be a URL, file name, or HTML fragmentscripts
: a string or array of strings, containing file names or URLs that will be inserted as<script>
tagsconfig
: see belowcallback
: takes two argumentserrors
: eithernull
, if nothing goes wrong, or an array of errorswindow
: a brand newwindow
, if there were no loading errors
Example:
jsdom;
If you would like to specify a configuration object only:
jsdom;
config.html
: a HTML fragmentconfig.file
: a file which jsdom will load HTML from; the resulting window'slocation.href
will be afile://
URL.config.url
: sets the resulting window'slocation.href
; ifconfig.html
andconfig.file
are not provided, jsdom will load HTML from this URL.config.scripts
: seescripts
above.config.src
: an array of JavaScript strings that will be evaluated against the resulting document. Similar toscripts
, but it accepts JavaScript instead of paths/URLs.config.jar
: a custom cookie jar, if desired; see mikeal/request documentation.config.level
: either1
,2
,3
, or'living'
, to restrict yourselves to features in certain DOM specifications. The default is'living'
.config.document
: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 to127.0.0.1
.
config.features
: seeFlexibility
section below. Note: the default feature set for jsdom.env does not include fetching remote JavaScript and executing it. This is something that you will need to carefully enable yourself.config.done
,config.loaded
,config.created
: see below.
Note that at least one of the callbacks (done
, loaded
, or created
) is required, as is one of html
, file
, or url
.
Initialization lifecycle
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
and/or loaded
callbacks:
created(error, window)
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.
If the 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(errors, window)
The 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.
If errors
is non-null
, it will contain an array of all JavaScript errors that occured during script execution. window
will still be passed, however.
done(errors, window)
Now that you know about created
and loaded
, you can see that done
is essentially both of them smashed together:
- If window creation succeeds and no
<script>
s cause errors, thenerrors
will be null, andwindow
will be usable. - If window creation succeeds but there are script errors, then
errors
will be an array containing those errors, butwindow
will still be usable. - If window creation fails, then
errors
will be an array containing the creation error, andwindow
will not be passed.
Migrating from before v1.0.0
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.
On running scripts and being safe
By default, jsdom.env
will not process and run external JavaScript, since our sandbox is not foolproof. That is, code running inside the DOM's <script>
s can, if it tries hard enough, get access to the Node environment, and thus to your machine. If you want to (carefully!) enable running JavaScript, you can use jsdom.jsdom
, jsdom.jQueryify
, or modify the defaults passed to jsdom.env
.
jsdom.jsdom
For the hardcore: The 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 = jsdom;var doc = ;var window = docparentWindow;
-
markup
is a HTML document to be parsed. You can also passundefined
to get the basic document, equivalent to what a browser will give if you open up an empty.html
file. -
options
: see the explanation of theconfig
object above.
Flexibility
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 Document
s before they are created. These features are baked into the DOMImplementation
that every Document
has, and may be tweaked in two ways:
- When you create a new
Document
, by overriding the configuration:
var jsdom = jsdom;var doc = ;
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).
- Before creating any documents, you can modify the defaults for all future documents:
defaultDocumentFeatures = FetchExternalResources: "script" ProcessExternalResources: false;
External Resources
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.
FetchExternalResources
- Default:
["script"]
- Allowed:
["script", "img", "css", "frame", "iframe", "link"]
orfalse
- Default for
jsdom.env
:false
Enables/disables fetching files over the file system/HTTP
ProcessExternalResources
- Default:
["script"]
- Allowed:
["script"]
orfalse
- Default for
jsdom.env
:false
Enables/disables JavaScript execution
SkipExternalResources
- Default:
false
(allow all) - Allowed:
/url to be skipped/
orfalse
- Example:
/http:\/\/example.org/js/bad\.js/
Filters resource downloading and processing to disallow those maching the given regular expression
Canvas
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 <div>
s.
More Examples
Creating a browser-like Window
var jsdom = jsdom;var document = ;var window = documentparentWindow; console;// output: "<html><head></head><body>hello world</body></html>" console;// output: 1024 console;// outputs: function
jQueryify
var jsdom = ;var window = jsdomparentWindow; jsdom;
Passing objects to scripts inside the page
var jsdom = jsdom;var window = parentWindow; window__myObject = foo: "bar" ; var scriptEl = windowdocument;scriptElsrc = "anotherScript.js";windowdocumentbody; // anotherScript.js will have the ability to read `window.__myObject`, even// though it originated in Node!
What Standards Does jsdom Support, Exactly?
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 Node
APIs, 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
Contextify is a dependency of jsdom, used for running <script>
tags within the page. In other words, it allows jsdom, which is run in Node.js, to run strings of JavaScript in an isolated environment that pretends to be a browser environment instead of a server. You can see how this is an important feature.
Unfortunately, doing this kind of magic requires C++. And in Node.js, using C++ from JavaScript means using "native modules." Native modules are compiled at installation time so that they work precisely for your machine; that is, you don't download a contextify binary from npm, but instead build one locally after downloading the source from npm.
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:
Windows
- The latest version of Node.js for Windows
- A copy of Visual Studio Express 2013 for Windows Desktop
- A copy of Python 2.7, installed in the default location of
C:\Python27
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!
Mac
- XCode needs to be installed
- "Command line tools for XCode" need to be installed
- Launch XCode once to accept the license, etc. and ensure it's properly installed
Linux
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.