Research
Security News
Malicious npm Package Typosquats react-login-page to Deploy Keylogger
Socket researchers unpack a typosquatting package with malicious code that logs keystrokes and exfiltrates sensitive data to a remote server.
happy-dom
Advanced tools
Package description
happy-dom is a fast and lightweight DOM implementation for Node.js. It is designed to be compatible with the browser's DOM API, making it useful for server-side rendering, testing, and other scenarios where a DOM is needed outside of a browser environment.
DOM Manipulation
happy-dom allows you to create and manipulate DOM elements just like you would in a browser environment. This is useful for server-side rendering and testing.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
const div = document.createElement('div');
div.textContent = 'Hello, World!';
document.body.appendChild(div);
console.log(document.body.innerHTML); // <div>Hello, World!</div>
Event Handling
happy-dom supports event handling, allowing you to add event listeners and dispatch events. This is useful for testing event-driven code.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
const button = document.createElement('button');
button.textContent = 'Click me';
button.addEventListener('click', () => {
console.log('Button clicked!');
});
document.body.appendChild(button);
// Simulate a click event
const event = new window.Event('click');
button.dispatchEvent(event); // Button clicked!
Querying DOM Elements
happy-dom allows you to query DOM elements using methods like `querySelector` and `querySelectorAll`. This is useful for selecting and manipulating specific elements in the DOM.
const { Window } = require('happy-dom');
const window = new Window();
const document = window.document;
document.body.innerHTML = '<div class="test">Hello</div><div class="test">World</div>';
const elements = document.querySelectorAll('.test');
console.log(elements.length); // 2
console.log(elements[0].textContent); // Hello
console.log(elements[1].textContent); // World
jsdom is another popular DOM implementation for Node.js. It provides a more complete and detailed implementation of the DOM and other web standards. However, it is generally slower and more resource-intensive compared to happy-dom.
cheerio is a fast, flexible, and lean implementation of core jQuery designed specifically for the server. It is not a full DOM implementation but provides a subset of jQuery functionality for parsing and manipulating HTML. It is faster and more lightweight than jsdom but less feature-rich.
linkedom is a lightweight and fast DOM implementation for Node.js. It aims to be a minimalistic alternative to jsdom, providing essential DOM functionalities with better performance. It is similar to happy-dom in terms of performance and use cases.
Readme
A "jsdom" alternative with support for server side rendering of web components.
As shadow roots are closed, this DOM supports opening them up by providing an option. When the shadow roots are opened up, Happy DOM will scope the HTML and CSS.
Custom Elements (Web Components)
Shadow Root (Shadow DOM)
Mutation Observer
Tree Walker
Fetch
And much more..
npm install happy-dom
Happy DOM provide with a utility for server side rendering. The utility will create a VM context, which is an isolated environment for where the script and DOM can be executed.
Importing dependencies is not supported by the VM script. Therefore scripts with imports has to be bundled with a tool like Webpack in order to be executed within the virtual machine.
import { VMContext } from 'happy-dom';
import { Script } from 'vm';
const vm = new VMContext();
const html = `
<html>
<head>
<title>Test page</title>
</head>
<body>
<div class="myContainer">
<!–– Content will be added here -->
</div>
</body>
</html>
`;
const script = new Script(`
const element = document.createElement('div');
const myContainer = document.querySelector('.myContainer');
element.innerHTML = 'Test';
myContainer.appendChild(element);
`);
const url = 'http://localhost:8080';
const openShadowRoots = true;
const result = vm.render({ html, script, url, openShadowRoots });
// Will output HTML with a div element inside the "myContainer" element
console.log(result);
This section will explain how to create a synchronous DOM for parsing HTML and much more.
Note: You might have to import the Window class as a single import if you wish to use it client side. Path: "happy-dom/lib/Window" .
import { Window } from 'happy-dom';
const window = new Window();
const document = window.document;
document.body.innerHTML = `
<div class="myContainer">Test</div>
`;
const myContainer = document.querySelector('.myContainer');
// Will output "Test"
console.log(myContainer.innerHTML);
The asynchronous DOM will add features like "fetch", "setTimeout", "setInterval" etc. on top of the synchronous DOM.
An asynchronous DOM is useful when running scripts inside of it. This is usually done within a VM context. See the "Manually Setup a VM Context" section for an example on how to set this up.
Note: The asynchronous DOM has a dependency to "node-fetch", so it will not work client side.
import { AsyncWindow } from 'happy-dom';
const window = new AsyncWindow();
const document = window.document;
document.body.innerHTML = `
<div class="myContainer">Test</div>
`;
window.fetch('http://localhost:8080/json').then(response => {
response.json().then(data => {
const myContainer = document.querySelector('.myContainer');
myContainer.innerHTML = data.test;
})
});
window.whenAsynComplete().then(() => {
const myContainer = document.querySelector('.myContainer');
// Will output the value in "data.test"
console.log(myContainer.innerHTML);
});
The bellow example will show you how to setup a Node VM context.
import { AsyncWindow } from 'happy-dom';
import { Script, createContext } from 'vm';
const asyncWindow = new AsyncWindow();
const global = Object.assign({}, asyncWindow, { window: asyncWindow });
const context = createContext(global);
const window = context.window;
const html = `
<html>
<head>
<title>Test page</title>
</head>
<body>
<div class="myContainer">
<!–– Content will be added here -->
</div>
</body>
</html>
`;
const script = new Script(`
const element = document.createElement('div');
const myContainer = document.querySelector('.myContainer');
element.innerHTML = 'Test';
myContainer.appendChild(element);
`);
window.location.href = 'http://localhost:8080';
window.shadowRootRenderOptions.openShadowRoots = true;
window.whenAsyncComplete().then(() => {
const myContainer = window.document.querySelector('.myContainer div');
// Will output "Test"
console.log(myContainer.innerHTML);
});
document.write(html);
script.runInContext(context);
Happy DOM supports the most common functionality of a DOM, but there are some features that are not supported yet.
If you have a need for a missing feature or if you have found a bug, please let me know, and I will do my best to fix it.
Version | Date | Description |
---|---|---|
0.2.0 | 2019-09-20 | Adds support for SVGSVGElement, SVGElement and SVGGraphicsElement. |
0.1.0 | 2019-09-19 | Adds support for HTMLInputElement, HTMLTextAreaElement, HTMLFormElement, Range and DOMRect (bounding client rect). |
0.0.1 | 2019-09-13 | Initial release. |
npm install
npm run compile
npm run watch
FAQs
Unknown package
We found that happy-dom demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket researchers unpack a typosquatting package with malicious code that logs keystrokes and exfiltrates sensitive data to a remote server.
Security News
The JavaScript community has launched the e18e initiative to improve ecosystem performance by cleaning up dependency trees, speeding up critical parts of the ecosystem, and documenting lighter alternatives to established tools.
Product
Socket now supports four distinct alert actions instead of the previous two, and alert triaging allows users to override the actions taken for all individual alerts.