Socket
Socket
Sign inDemoInstall

happy-dom

Package Overview
Dependencies
3
Maintainers
1
Versions
558
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

happy-dom


Version published
Weekly downloads
643K
decreased by-18.76%
Maintainers
1
Created
Weekly downloads
 

Package description

What is happy-dom?

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.

What are happy-dom's main functionalities?

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

Other packages similar to happy-dom

Readme

Source

Happy DOM

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.

DOM Features

  • Custom Elements (Web Components)

  • Shadow Root (Shadow DOM)

  • Mutation Observer

  • Tree Walker

  • Fetch

    And much more..

How to Install

npm install happy-dom

Usage

Server Side Rendering

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.

Example

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);

Create a Synchronous DOM

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);

Create an Asynchronous DOM

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);
});

Manually Setup a VM Context

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);

Known Limitations

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.

Release Notes

VersionDateDescription
0.0.12019-09-13Initial release.

How to Develop

Installation

npm install

Compilation

npm run compile

Run Watcher

npm run watch

Keywords

FAQs

Last updated on 15 Sep 2019

Did you know?

Socket

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.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc