CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-puppeteer

A high-level API to control headless Chrome over the DevTools Protocol

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

page-interaction.mddocs/

Page Navigation & Interaction

Page-level operations for navigation, content manipulation, element interaction, and JavaScript execution within browser tabs.

Capabilities

Page Navigation

Navigate to URLs, manage page history, and control page lifecycle.

/**
 * Navigate to a URL
 * @param url - URL to navigate to
 * @param options - Navigation options
 * @returns Promise resolving to main response or null
 */
goto(url: string, options?: GoToOptions): Promise<HTTPResponse | null>;

/**
 * Reload the current page
 * @param options - Reload options
 * @returns Promise resolving to main response or null
 */
reload(options?: WaitForOptions): Promise<HTTPResponse | null>;

/**
 * Navigate back in browser history
 * @param options - Navigation options
 * @returns Promise resolving to main response or null
 */
goBack(options?: WaitForOptions): Promise<HTTPResponse | null>;

/**
 * Navigate forward in browser history  
 * @param options - Navigation options
 * @returns Promise resolving to main response or null
 */
goForward(options?: WaitForOptions): Promise<HTTPResponse | null>;

/**
 * Get current page URL
 * @returns Current URL as string
 */
url(): string;

/**
 * Get page title
 * @returns Promise resolving to page title
 */
title(): Promise<string>;

interface GoToOptions {
  /** Maximum navigation time in milliseconds */
  timeout?: number;
  /** When to consider navigation complete */
  waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2" | Array<"load" | "domcontentloaded" | "networkidle0" | "networkidle2">;
  /** Referer header value */
  referer?: string;
}

interface WaitForOptions {
  /** Maximum wait time in milliseconds */
  timeout?: number;
  /** When to consider navigation complete */
  waitUntil?: "load" | "domcontentloaded" | "networkidle0" | "networkidle2" | Array<"load" | "domcontentloaded" | "networkidle0" | "networkidle2">;
}

Usage Examples:

// Basic navigation
await page.goto("https://example.com");

// Navigation with options
await page.goto("https://example.com/login", {
  waitUntil: "networkidle0",  // Wait until no network requests for 500ms
  timeout: 10000             // 10 second timeout
});

// Navigate with history
await page.goto("https://example.com/page1");
await page.goto("https://example.com/page2");
await page.goBack();  // Back to page1
await page.goForward(); // Forward to page2

// Page info
const url = page.url();
const title = await page.title();

Content Management

Get and set page content, including HTML manipulation.

/**
 * Get full page HTML content
 * @returns Promise resolving to HTML string
 */
content(): Promise<string>;

/**
 * Set page HTML content
 * @param html - HTML content to set
 * @param options - Content setting options
 * @returns Promise that resolves when content is set
 */
setContent(html: string, options?: WaitForOptions): Promise<void>;

Usage Examples:

// Get page content
const html = await page.content();
console.log(html);

// Set custom content
await page.setContent(`
  <html>
    <body>
      <h1>Custom Page</h1>
      <p>This is custom content</p>
    </body>
  </html>
`);

Element Selection

Find and select elements using CSS selectors or XPath.

/**
 * Find single element matching selector
 * @param selector - CSS selector
 * @returns Promise resolving to ElementHandle or null
 */
$(selector: string): Promise<ElementHandle | null>;

/**
 * Find all elements matching selector
 * @param selector - CSS selector
 * @returns Promise resolving to array of ElementHandles
 */
$$(selector: string): Promise<ElementHandle[]>;

/**
 * Evaluate function on single element
 * @param selector - CSS selector
 * @param pageFunction - Function to evaluate on element
 * @param args - Arguments to pass to function
 * @returns Promise resolving to function result
 */
$eval<R>(
  selector: string, 
  pageFunction: (element: Element, ...args: any[]) => R,
  ...args: any[]
): Promise<R>;

/**
 * Evaluate function on all matching elements
 * @param selector - CSS selector
 * @param pageFunction - Function to evaluate on elements
 * @param args - Arguments to pass to function
 * @returns Promise resolving to function result
 */
$$eval<R>(
  selector: string,
  pageFunction: (elements: Element[], ...args: any[]) => R,
  ...args: any[]
): Promise<R>;

Usage Examples:

// Find single element
const searchBox = await page.$("#search-input");
if (searchBox) {
  await searchBox.type("query");
}

// Find multiple elements
const links = await page.$$("a");
console.log(`Found ${links.length} links`);

// Evaluate on single element
const text = await page.$eval("#title", el => el.textContent);

// Evaluate on multiple elements
const linkData = await page.$$eval("a", anchors => 
  anchors.map(a => ({
    text: a.textContent?.trim(),
    href: a.href
  }))
);

Element Interaction

Click, type, and interact with page elements using selectors.

/**
 * Click element matching selector
 * @param selector - CSS selector
 * @param options - Click options
 * @returns Promise that resolves when click completes
 */
click(selector: string, options?: ClickOptions): Promise<void>;

/**
 * Focus element matching selector
 * @param selector - CSS selector
 * @returns Promise that resolves when focus completes
 */
focus(selector: string): Promise<void>;

/**
 * Hover over element matching selector
 * @param selector - CSS selector
 * @returns Promise that resolves when hover completes
 */
hover(selector: string): Promise<void>;

/**
 * Select options in select element
 * @param selector - CSS selector for select element
 * @param values - Option values to select
 * @returns Promise resolving to selected values
 */
select(selector: string, ...values: string[]): Promise<string[]>;

/**
 * Tap element (touch interaction)
 * @param selector - CSS selector
 * @returns Promise that resolves when tap completes
 */
tap(selector: string): Promise<void>;

/**
 * Type text into element
 * @param selector - CSS selector
 * @param text - Text to type
 * @param options - Typing options
 * @returns Promise that resolves when typing completes
 */
type(selector: string, text: string, options?: TypeOptions): Promise<void>;

interface ClickOptions {
  /** Mouse button to click */
  button?: "left" | "right" | "middle";
  /** Number of clicks */
  clickCount?: number;
  /** Delay between mousedown and mouseup */
  delay?: number;
  /** Offset from element center */
  offset?: {x: number; y: number};
}

interface TypeOptions {
  /** Delay between key presses */
  delay?: number;
}

Usage Examples:

// Click elements
await page.click("#submit-button");
await page.click(".menu-item", { button: "right" }); // Right click

// Type text
await page.type("#username", "john_doe");
await page.type("#password", "secret123", { delay: 100 });

// Select options
await page.select("#country", "US", "CA"); // Multi-select

// Other interactions
await page.focus("#search-input");
await page.hover(".tooltip-trigger");
await page.tap("#mobile-button"); // Touch interaction

Waiting Operations

Wait for various conditions before proceeding with automation.

/**
 * Wait for element to appear
 * @param selector - CSS selector
 * @param options - Wait options
 * @returns Promise resolving to ElementHandle
 */
waitForSelector(
  selector: string, 
  options?: WaitForSelectorOptions
): Promise<ElementHandle>;

/**
 * Wait for function to return truthy value
 * @param pageFunction - Function to evaluate repeatedly
 * @param options - Wait options
 * @param args - Arguments to pass to function
 * @returns Promise resolving to JSHandle of result
 */
waitForFunction<R>(
  pageFunction: (...args: any[]) => R,
  options?: WaitForFunctionOptions,
  ...args: any[]
): Promise<JSHandle<R>>;

/**
 * Wait for navigation to complete
 * @param options - Wait options
 * @returns Promise resolving to main response or null
 */
waitForNavigation(options?: WaitForOptions): Promise<HTTPResponse | null>;

/**
 * Wait for network to be idle
 * @param options - Wait options
 * @returns Promise that resolves when network is idle
 */
waitForNetworkIdle(options?: WaitForNetworkIdleOptions): Promise<void>;

/**
 * Wait for request matching predicate
 * @param urlOrPredicate - URL string or predicate function
 * @param options - Wait options
 * @returns Promise resolving to HTTPRequest
 */
waitForRequest(
  urlOrPredicate: string | ((request: HTTPRequest) => boolean),
  options?: WaitTimeoutOptions
): Promise<HTTPRequest>;

/**
 * Wait for response matching predicate
 * @param urlOrPredicate - URL string or predicate function
 * @param options - Wait options
 * @returns Promise resolving to HTTPResponse
 */
waitForResponse(
  urlOrPredicate: string | ((response: HTTPResponse) => boolean),
  options?: WaitTimeoutOptions
): Promise<HTTPResponse>;

interface WaitForSelectorOptions {
  /** Whether element should be visible */
  visible?: boolean;
  /** Whether element should be hidden */
  hidden?: boolean;
  /** Maximum wait time */
  timeout?: number;
}

interface WaitForFunctionOptions {
  /** Maximum wait time */
  timeout?: number;
  /** Polling interval */
  polling?: "raf" | "mutation" | number;
}

interface WaitForNetworkIdleOptions {
  /** Maximum wait time */
  timeout?: number;
  /** Idle time threshold */
  idleTime?: number;
}

interface WaitTimeoutOptions {
  /** Maximum wait time */
  timeout?: number;
}

Usage Examples:

// Wait for elements
await page.waitForSelector("#submit-button");
await page.waitForSelector(".loading", { hidden: true });

// Wait for custom conditions
await page.waitForFunction(() => window.dataLoaded === true);
await page.waitForFunction(
  (selector) => document.querySelector(selector)?.scrollHeight > 1000,
  {},
  "#content"
);

// Wait for navigation
const responsePromise = page.waitForNavigation();
await page.click("#link");
const response = await responsePromise;

// Wait for network
await page.waitForResponse("https://api.example.com/data");
await page.waitForRequest(req => req.url().includes("/api/"));

JavaScript Evaluation

Execute JavaScript code in the page context.

/**
 * Evaluate JavaScript function in page context
 * @param pageFunction - Function to evaluate
 * @param args - Arguments to pass to function
 * @returns Promise resolving to function result
 */
evaluate<R>(
  pageFunction: (...args: any[]) => R,
  ...args: any[]
): Promise<R>;

/**
 * Evaluate function and get handle to result
 * @param pageFunction - Function to evaluate
 * @param args - Arguments to pass to function
 * @returns Promise resolving to JSHandle of result
 */
evaluateHandle<R>(
  pageFunction: (...args: any[]) => R,
  ...args: any[]
): Promise<JSHandle<R>>;

/**
 * Add script to be evaluated on every document creation
 * @param pageFunction - Function to evaluate
 * @param args - Arguments to pass to function
 * @returns Promise that resolves when script is added
 */
evaluateOnNewDocument(
  pageFunction: (...args: any[]) => void,
  ...args: any[]
): Promise<void>;

Usage Examples:

// Evaluate simple expressions
const title = await page.evaluate(() => document.title);
const windowSize = await page.evaluate(() => ({
  width: window.innerWidth,
  height: window.innerHeight
}));

// Pass arguments to evaluation
const result = await page.evaluate((x, y) => x + y, 2, 3); // Returns 5

// Get handle to complex objects
const windowHandle = await page.evaluateHandle(() => window);
const locationHandle = await windowHandle.getProperty("location");

// Add initialization scripts
await page.evaluateOnNewDocument(() => {
  // This runs on every page load
  window.myGlobalVar = "initialized";
});

Script and Style Management

Add external scripts and stylesheets to the page.

/**
 * Add script tag to page
 * @param options - Script tag options
 * @returns Promise resolving to ElementHandle of script tag
 */
addScriptTag(options: AddTagOptions): Promise<ElementHandle>;

/**
 * Add style tag to page
 * @param options - Style tag options
 * @returns Promise resolving to ElementHandle of style tag
 */
addStyleTag(options: AddTagOptions): Promise<ElementHandle>;

interface AddTagOptions {
  /** URL of external resource */
  url?: string;
  /** Path to local file */
  path?: string;
  /** Inline content */
  content?: string;
  /** Script type (for script tags) */
  type?: string;
}

Usage Examples:

// Add external script
await page.addScriptTag({
  url: "https://code.jquery.com/jquery-3.6.0.min.js"
});

// Add inline script
await page.addScriptTag({
  content: `
    window.utils = {
      formatDate: (date) => date.toISOString()
    };
  `
});

// Add stylesheet
await page.addStyleTag({
  url: "https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.min.css"
});

// Add inline styles
await page.addStyleTag({
  content: `
    .highlight { background-color: yellow; }
    .hidden { display: none; }
  `
});

Page Context Information

Access page context, frames, and related browser objects.

/**
 * Get parent browser instance
 * @returns Browser instance
 */
browser(): Browser;

/**
 * Get browser context
 * @returns BrowserContext instance
 */
browserContext(): BrowserContext;

/**
 * Get page target
 * @returns Target instance
 */
target(): Target;

/**
 * Get main frame
 * @returns Frame instance
 */
mainFrame(): Frame;

/**
 * Get all frames in page
 * @returns Array of Frame instances
 */
frames(): Frame[];

/**
 * Get all web workers
 * @returns Array of WebWorker instances
 */
workers(): WebWorker[];

/**
 * Check if page is closed
 * @returns True if page is closed
 */
isClosed(): boolean;

Usage Examples:

// Access browser context
const browser = page.browser();
const context = page.browserContext();

// Work with frames
const mainFrame = page.mainFrame();
const allFrames = page.frames();

console.log(`Page has ${allFrames.length} frames`);

// Access workers
const workers = page.workers();
console.log(`Page has ${workers.length} web workers`);

// Check page state
if (!page.isClosed()) {
  await page.evaluate(() => console.log("Page is still open"));
}

Page Lifecycle

Close pages and handle page lifecycle events.

/**
 * Close the page
 * @param options - Close options
 * @returns Promise that resolves when page is closed
 */
close(options?: {runBeforeUnload?: boolean}): Promise<void>;

Usage Examples:

// Close page immediately
await page.close();

// Close page after running beforeunload handlers
await page.close({ runBeforeUnload: true });

Dialog Handling

Handle browser dialogs including alert, confirm, and prompt dialogs.

/**
 * Browser dialog (alert, confirm, prompt)
 */
class Dialog {
  /** Get dialog type */
  type(): DialogType;
  
  /** Get dialog message text */
  message(): string;
  
  /** Get default value for prompt dialogs */
  defaultValue(): string;
  
  /** Accept dialog with optional text for prompts */
  accept(promptText?: string): Promise<void>;
  
  /** Dismiss/cancel dialog */
  dismiss(): Promise<void>;
}

type DialogType = "alert" | "confirm" | "prompt" | "beforeunload";

Usage Examples:

// Handle dialogs using event listener
page.on("dialog", async (dialog) => {
  console.log(`Dialog type: ${dialog.type()}`);
  console.log(`Dialog message: ${dialog.message()}`);
  
  if (dialog.type() === "confirm") {
    await dialog.accept(); // Click OK
  } else if (dialog.type() === "prompt") {
    await dialog.accept("My response"); // Enter text and click OK
  } else {
    await dialog.dismiss(); // Click Cancel or close
  }
});

// Trigger dialog
await page.click("#show-alert");

// Or handle with waitForEvent
const dialogPromise = page.waitForEvent("dialog");
await page.click("#show-confirm");
const dialog = await dialogPromise;
await dialog.accept();

Install with Tessl CLI

npx tessl i tessl/npm-puppeteer

docs

browser-management.md

device-emulation.md

element-handling.md

index.md

input-interaction.md

locators-waiting.md

media-generation.md

network-control.md

page-interaction.md

performance-debugging.md

tile.json