Skip to content

Browser

David Ortner edited this page Sep 9, 2024 · 27 revisions

Browser represents an instance of a Happy DOM browser. The API is similar to the API for Puppeteer and Playwright.

Signature

class Browser implements IBrowser

Example 1

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

Example 2

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

Constructor

Parameter Type Description
options? object Browser options.
options.settings? IOptionalBrowserSettings Browser settings.
options.console? Console Console object. Each page will create an instance of VirtualConsole by default if not specified.

Properties

Property Modifiers Type Description
contexts readonly BrowserContext[] Browser contexts. Defaults to one main context.
settings readonly IBrowserSettings Browser settings. The settings can be modified runtime.
console readonly Console Console object sent in to the constructor.
defaultContext readonly BrowserContext Default context.

Methods

Method Return type Description
close() Promise<void> Closes the browser.
waitUntilComplete() Promise<void> Waits for all ongoing operations to complete. This includes operations done inside loaded pages, such as loading resources and executing scripts.
abort() Promise<void> Aborts all ongoing operations.
newIncognitoContext() BrowserContext Creates a new incognito context.
newPage() BrowserPage Creates a new page.
Clone this wiki locally