Skip to content

JSDOM

To emulate a browser-like environment, you may use JSDOM.

Quokka automatically detects usages of browser APIs and will automatically suggest to install and use JSDOM if required.

Alternatively, you may install JSDOM as either a global Quokka dependency to make it available for all Quokka projects, or else as a dependency in your project.

Terminal window
npm install jsdom

If you have installed JSOM manually, then you must also add the built-in jsdom-quokka-plugin to the plugins section of your Quokka configuration:

{
"plugins": ["jsdom-quokka-plugin"]
}

Configuration

If you need to, you may pass additional configuration options:

{
"plugins": ["jsdom-quokka-plugin"],
"jsdom": {
"file": "/html/file/path"
"html": "...",
"userAgent": "...",
"config": {...}
}
}

The jsdom.file setting allows to specify a path to any HTML file.

The jsdom.html setting allows to specify any HTML as a string.

The jsdom.config setting is the jsdom options setting.

If jsdom.file and jsdom.html is not provided, Quokka will attempt to load html for a file that has the same folder and base filename as your Quokka file with an .html extension. If no {quokkaFile}.html file exists, Quokka will attempt to load html from index.html in the same folder as your Quokka file. If no index.html is found, Quokka will set the document’s body to a single div with id of root (<div id="root"></div>).

Quokka jsdom default settings are shown below:

{
"plugins": ["jsdom-quokka-plugin"],
"jsdom": {
"userAgent": "quokka.js",
"config": {
"pretendToBeVisual": true,
"runScripts": "dangerously",
"url": "http://localhost/"
}
}
}

Inline Config Example

Quokka Scratch File

({
plugins: ['jsdom-quokka-plugin'],
jsdom: { html: `<div id="testDiv">Hello</div>` },
});
const testDiv = document.getElementById('testDiv');
console.log(testDiv.innerHTML);

Loading from HTML file Example

Html File (/test.html)

<html>
<head>
<title>This is my sample page.</title>
</head>
<body>
<p id="testDiv">Hello World</p>
</body>
</html>

Quokka Scratch File

({
plugins: ['jsdom-quokka-plugin'],
jsdom: { file: 'test.html' }, // Located in project root
});
const testDiv = document.getElementById('testDiv');
console.log(testDiv.innerHTML);

Web Canvas API

If you want to use HTMLCanvasElement objects with Quokka and jsdom then you must also install the canvas package in the same location as jsdom.

Terminal window
npm install canvas