-
-
Notifications
You must be signed in to change notification settings - Fork 210
Getting started
David Ortner edited this page Mar 16, 2024
·
15 revisions
npm install happy-dom
Happy DOM can be used as a simulated Browser or by using the Window class directly to quickly setup up a DOM.
A simple example of how to use the Window class. For more information, see the Window API documentation.
import { Window } from 'happy-dom';
const window = new Window({ url: 'https://localhost:8080' });
const document = window.document;
document.body.innerHTML = '<div class="container"></div>';
const container = document.querySelector('.container');
const button = document.createElement('button');
container.appendChild(button);
// Outputs "<div class="container"><button></button></div>"
console.log(document.body.innerHTML);
// Aborts any ongoing operations (such as fetch and timers)
await window.happyDOM.abort();
// Closes the window
window.close();
Two simple examples of how to use the Browser class. For more information, see the Browser API documentation.
import { Browser } from "happy-dom";
const browser = new Browser();
const page = browser.newPage();
page.url = 'https://example.com';
page.content = '<html><body>Hello world!</body></html>';
// Outputs "Hello world!"
console.log(page.mainFrame.document.body.textContent);
await browser.close();
import { Browser, BrowserErrorCaptureEnum } from 'happy-dom';
const browser = new Browser({ settings: { errorCapture: BrowserErrorCaptureEnum.processLevel } });
const page = browser.newPage();
// Navigates page
await page.goto('https://github.com/capricorn86');
// Clicks on link
page.mainFrame.document.querySelector('a[href*="capricorn86/happy-dom"]').click();
// Waits for all operations on the page to complete (fetch, timers etc.)
await page.waitUntilComplete();
// Outputs "GitHub - capricorn86/happy-dom: Happy DOM..."
console.log(page.mainFrame.document.title);
// Aborts all ongoing operations and closes the browser
await browser.close();