CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-puppeteer-core

A high-level API to control headless Chrome and Firefox browsers over the DevTools Protocol and WebDriver BiDi

94

1.02x
Overview
Eval results
Files

page-interaction.mddocs/

Page Navigation and Interaction

Complete page automation including navigation, element interaction, JavaScript execution, and content extraction.

Capabilities

Page Interface

Main interface for interacting with browser pages, providing navigation, content manipulation, and event handling.

interface Page extends EventEmitter {
  /** Navigate to URL */
  goto(url: string, options?: GoToOptions): Promise<HTTPResponse | null>;
  /** Reload current page */
  reload(options?: ReloadOptions): Promise<HTTPResponse | null>;
  /** Go back in history */
  goBack(options?: GoToOptions): Promise<HTTPResponse | null>;
  /** Go forward in history */
  goForward(options?: GoToOptions): Promise<HTTPResponse | null>;
  /** Set viewport size */
  setViewport(viewport: Viewport): Promise<void>;
  /** Get current viewport */
  viewport(): Viewport | null;
  /** Take screenshot */
  screenshot(options?: ScreenshotOptions): Promise<Buffer>;
  /** Generate PDF */
  pdf(options?: PDFOptions): Promise<Buffer>;
  /** Get page title */
  title(): Promise<string>;
  /** Get page URL */
  url(): string;
  /** Get page content as HTML */
  content(): Promise<string>;
  /** Set page content */
  setContent(html: string, options?: GoToOptions): Promise<void>;
  /** Evaluate JavaScript in page context */
  evaluate<T>(pageFunction: Function, ...args: any[]): Promise<T>;
  /** Evaluate JavaScript with handle return */
  evaluateHandle<T>(pageFunction: Function, ...args: any[]): Promise<JSHandle<T>>;
  /** Add script tag to page */
  addScriptTag(options: ScriptTagOptions): Promise<ElementHandle>;
  /** Add style tag to page */
  addStyleTag(options: StyleTagOptions): Promise<ElementHandle>;
  /** Expose function to page context */
  exposeFunction(name: string, puppeteerFunction: Function): Promise<void>;
  /** Remove exposed function */
  removeExposedFunction(name: string): Promise<void>;
  /** Set geolocation */
  setGeolocation(options: GeolocationOptions): Promise<void>;
  /** Set timezone */
  emulateTimezone(timezoneId: string): Promise<void>;
  /** Emulate media type */
  emulateMediaType(type?: "screen" | "print" | null): Promise<void>;
  /** Emulate media features */
  emulateMediaFeatures(features?: MediaFeature[]): Promise<void>;
  /** Emulate vision deficiency */
  emulateVisionDeficiency(type?: VisionDeficiency): Promise<void>;
  /** Set JavaScript enabled state */
  setJavaScriptEnabled(enabled: boolean): Promise<void>;
  /** Set offline mode */
  setOfflineMode(enabled: boolean): Promise<void>;
  /** Set request interception */
  setRequestInterception(value: boolean): Promise<void>;
  /** Set user agent */
  setUserAgent(userAgent: string, userAgentMetadata?: UserAgentMetadata): Promise<void>;
  /** Set extra HTTP headers */
  setExtraHTTPHeaders(headers: Record<string, string>): Promise<void>;
  /** Authenticate with HTTP credentials */
  authenticate(credentials: Credentials | null): Promise<void>;
  /** Get/set cookies */
  cookies(...urls: string[]): Promise<Cookie[]>;
  setCookie(...cookies: CookieParam[]): Promise<void>;
  deleteCookie(...cookies: DeleteCookiesRequest[]): Promise<void>;
  /** Click element */
  click(selector: string, options?: ClickOptions): Promise<void>;
  /** Focus element */
  focus(selector: string): Promise<void>;
  /** Hover element */
  hover(selector: string): Promise<void>;
  /** Select options */
  select(selector: string, ...values: string[]): Promise<string[]>;
  /** Tap element (mobile) */
  tap(selector: string): Promise<void>;
  /** Type text */
  type(selector: string, text: string, options?: TypeOptions): Promise<void>;
  /** Wait for selector */
  waitForSelector(selector: string, options?: WaitForSelectorOptions): Promise<ElementHandle | null>;
  /** Wait for XPath */
  waitForXPath(xpath: string, options?: WaitForSelectorOptions): Promise<ElementHandle | null>;
  /** Wait for function result */
  waitForFunction(pageFunction: Function, options?: WaitForFunctionOptions, ...args: any[]): Promise<JSHandle>;
  /** Wait for request */
  waitForRequest(urlOrPredicate: string | Function, options?: WaitForOptions): Promise<HTTPRequest>;
  /** Wait for response */
  waitForResponse(urlOrPredicate: string | Function, options?: WaitForOptions): Promise<HTTPResponse>;
  /** Wait for navigation */
  waitForNavigation(options?: WaitForOptions): Promise<HTTPResponse | null>;
  /** Wait for timeout */
  waitForTimeout(milliseconds: number): Promise<void>;
  /** Query selector */
  $(selector: string): Promise<ElementHandle | null>;
  /** Query selector all */
  $$(selector: string): Promise<ElementHandle[]>;
  /** Evaluate with selector */
  $eval<T>(selector: string, pageFunction: Function, ...args: any[]): Promise<T>;
  /** Evaluate with selector all */
  $$eval<T>(selector: string, pageFunction: Function, ...args: any[]): Promise<T>;
  /** XPath query */
  $x(expression: string): Promise<ElementHandle[]>;
  /** Get browser instance */
  browser(): Browser;
  /** Get browser context */
  browserContext(): BrowserContext;
  /** Get main frame */
  mainFrame(): Frame;
  /** Get all frames */
  frames(): Frame[];
  /** Get all workers */
  workers(): WebWorker[];
  /** Create CDP session */
  createCDPSession(): Promise<CDPSession>;
  /** Get target */
  target(): Target;
  /** Get keyboard interface */
  keyboard: Keyboard;
  /** Get mouse interface */
  mouse: Mouse;
  /** Get touchscreen interface */
  touchscreen: Touchscreen;
  /** Get coverage interface */
  coverage: Coverage;
  /** Get tracing interface */
  tracing: Tracing;
  /** Get accessibility interface */
  accessibility: Accessibility;
  /** Check if closed */
  isClosed(): boolean;
  /** Close page */
  close(options?: PageCloseOptions): Promise<void>;
  /** Check if JavaScript enabled */
  isJavaScriptEnabled(): boolean;
  /** Check if drag interception enabled */
  isDragInterceptionEnabled(): boolean;
  /** Set drag interception */
  setDragInterception(enabled: boolean): Promise<void>;
}

interface GoToOptions {
  timeout?: number;
  waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
  referer?: string;
}

interface ReloadOptions {
  timeout?: number;
  waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
}

type PuppeteerLifeCycleEvent = "load" | "domcontentloaded" | "networkidle0" | "networkidle2";

interface ScreenshotOptions {
  type?: "png" | "jpeg" | "webp";
  path?: string;
  fullPage?: boolean;
  clip?: BoundingBox;
  quality?: number;
  omitBackground?: boolean;
  encoding?: "base64" | "binary";
  captureBeyondViewport?: boolean;
  fromSurface?: boolean;
}

interface PDFOptions {
  scale?: number;
  displayHeaderFooter?: boolean;
  headerTemplate?: string;
  footerTemplate?: string;
  printBackground?: boolean;
  landscape?: boolean;
  pageRanges?: string;
  format?: PaperFormat;
  width?: string | number;
  height?: string | number;
  preferCSSPageSize?: boolean;
  margin?: {
    top?: string | number;
    right?: string | number;
    bottom?: string | number;
    left?: string | number;
  };
  path?: string;
  timeout?: number;
  tagged?: boolean;
  waitForFonts?: boolean;
}

type PaperFormat = "Letter" | "Legal" | "Tabloid" | "Ledger" | "A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "A6";

interface ScriptTagOptions {
  url?: string;
  path?: string;
  content?: string;
  type?: string;
  id?: string;
}

interface StyleTagOptions {
  url?: string;
  path?: string;
  content?: string;
}

interface GeolocationOptions {
  latitude: number;
  longitude: number;
  accuracy?: number;
}

interface MediaFeature {
  name: string;
  value: string;
}

type VisionDeficiency = "achromatopsia" | "blurredVision" | "deuteranopia" | "protanopia" | "tritanopia" | null;

interface UserAgentMetadata {
  brands?: Array<{ brand: string; version: string }>;
  fullVersionList?: Array<{ brand: string; version: string }>;
  fullVersion?: string;
  platform?: string;
  platformVersion?: string;
  architecture?: string;
  model?: string;
  mobile?: boolean;
  bitness?: string;
  wow64?: boolean;
}

interface Credentials {
  username: string;
  password: string;
}

interface CookieParam {
  name: string;
  value: string;
  url?: string;
  domain?: string;
  path?: string;
  secure?: boolean;
  httpOnly?: boolean;
  sameSite?: "Strict" | "Lax" | "None";
  expires?: number;
  priority?: "Low" | "Medium" | "High";
  sameParty?: boolean;
  sourceScheme?: "Unset" | "NonSecure" | "Secure";
  partitionKey?: string;
}

interface DeleteCookiesRequest {
  name: string;
  url?: string;
  domain?: string;
  path?: string;
  partitionKey?: string;
}

interface ClickOptions {
  button?: "left" | "right" | "middle";
  clickCount?: number;
  delay?: number;
  offset?: { x: number; y: number };
}

interface TypeOptions {
  delay?: number;
}

interface WaitForSelectorOptions {
  visible?: boolean;
  hidden?: boolean;
  timeout?: number;
}

interface WaitForFunctionOptions {
  timeout?: number;
  polling?: "raf" | "mutation" | number;
}

interface WaitForOptions {
  timeout?: number;
  waitUntil?: PuppeteerLifeCycleEvent | PuppeteerLifeCycleEvent[];
}

interface PageCloseOptions {
  runBeforeUnload?: boolean;
}

Usage Examples:

import puppeteer from "puppeteer-core";

const browser = await puppeteer.launch({ executablePath: "/path/to/chrome" });
const page = await browser.newPage();

// Navigation
await page.goto("https://example.com", { 
  waitUntil: "networkidle0",
  timeout: 30000 
});

await page.setViewport({ width: 1024, height: 768 });

// Content extraction
const title = await page.title();
const content = await page.content();
const url = page.url();

// Screenshots and PDFs
await page.screenshot({ 
  path: "screenshot.png", 
  fullPage: true 
});

await page.pdf({ 
  path: "page.pdf", 
  format: "A4",
  printBackground: true 
});

// JavaScript evaluation
const result = await page.evaluate(() => {
  return document.querySelector("h1")?.textContent;
});

const handle = await page.evaluateHandle(() => document.body);

// Form interaction
await page.type("#username", "user@example.com");
await page.type("#password", "password123");
await page.click("#login-button");

// Wait for navigation
await page.waitForNavigation({ waitUntil: "networkidle0" });

// Cookies
await page.setCookie({
  name: "session",
  value: "abc123",
  domain: "example.com"
});

const cookies = await page.cookies();

await browser.close();

Page Events

The Page class emits various events during its lifecycle:

interface PageEvents {
  /** Emitted when page closes */
  "close": () => void;
  /** Emitted when page crashes */
  "error": (error: Error) => void;
  /** Emitted when page loads */
  "load": () => void;
  /** Emitted when DOM content loads */
  "domcontentloaded": () => void;
  /** Emitted when JavaScript console API called */
  "console": (message: ConsoleMessage) => void;
  /** Emitted when JavaScript dialog appears */
  "dialog": (dialog: Dialog) => void;
  /** Emitted when request starts */
  "request": (request: HTTPRequest) => void;
  /** Emitted when response received */
  "response": (response: HTTPResponse) => void;
  /** Emitted when request fails */
  "requestfailed": (request: HTTPRequest) => void;
  /** Emitted when request finishes */
  "requestfinished": (request: HTTPRequest) => void;
  /** Emitted when frame attaches */
  "frameattached": (frame: Frame) => void;
  /** Emitted when frame detaches */
  "framedetached": (frame: Frame) => void;
  /** Emitted when frame navigates */
  "framenavigated": (frame: Frame) => void;
  /** Emitted when worker created */
  "workercreated": (worker: WebWorker) => void;
  /** Emitted when worker destroyed */
  "workerdestroyed": (worker: WebWorker) => void;
  /** Emitted when page metrics updated */
  "metrics": (data: { title: string; metrics: Metrics }) => void;
  /** Emitted when file chooser appears */
  "filechooser": (fileChooser: FileChooser) => void;
  /** Emitted on popup */
  "popup": (page: Page) => void;
}

interface Metrics {
  Timestamp?: number;
  AudioHandlers?: number;
  Documents?: number;
  Frames?: number;
  JSEventListeners?: number;
  Nodes?: number;
  LayoutCount?: number;
  RecalcStyleCount?: number;
  LayoutDuration?: number;
  RecalcStyleDuration?: number;
  ScriptDuration?: number;
  TaskDuration?: number;
  JSHeapUsedSize?: number;
  JSHeapTotalSize?: number;
}

Console Messages

Handle browser console output:

interface ConsoleMessage {
  type(): "log" | "debug" | "info" | "error" | "warning" | "dir" | "dirxml" | "table" | "trace" | "clear" | "startGroup" | "startGroupCollapsed" | "endGroup" | "assert" | "profile" | "profileEnd" | "count" | "timeEnd";
  text(): string;
  args(): JSHandle[];
  location(): ConsoleMessageLocation;
  stackTrace(): ConsoleMessageLocation[];
}

interface ConsoleMessageLocation {
  url?: string;
  lineNumber?: number;
  columnNumber?: number;
}

Dialog Handling

Handle JavaScript dialogs (alert, confirm, prompt):

interface Dialog {
  type(): "alert" | "beforeunload" | "confirm" | "prompt";
  message(): string;
  defaultValue(): string;
  accept(promptText?: string): Promise<void>;
  dismiss(): Promise<void>;
}

Usage Examples:

// Handle dialogs
page.on("dialog", async (dialog) => {
  console.log("Dialog type:", dialog.type());
  console.log("Dialog message:", dialog.message());
  
  if (dialog.type() === "confirm") {
    await dialog.accept();
  } else {
    await dialog.dismiss();
  }
});

// Handle console messages
page.on("console", (msg) => {
  console.log(`PAGE LOG: ${msg.text()}`);
});

// Handle page events
page.on("load", () => console.log("Page loaded"));
page.on("requestfailed", (req) => {
  console.log("Request failed:", req.url());
});

File Handling

Handle file uploads and downloads:

interface FileChooser {
  isMultiple(): boolean;
  accept(filePaths: string[]): Promise<void>;
  cancel(): Promise<void>;
}

Usage Examples:

// Handle file chooser
const [fileChooser] = await Promise.all([
  page.waitForEvent("filechooser"),
  page.click("#upload-button")
]);

await fileChooser.accept(["/path/to/file.txt"]);

// Set download behavior
const client = await page.createCDPSession();
await client.send("Page.setDownloadBehavior", {
  behavior: "allow",
  downloadPath: "/path/to/downloads"
});

Advanced Page Features

Additional page capabilities for complex scenarios:

interface Coverage {
  startJSCoverage(options?: JSCoverageOptions): Promise<void>;
  stopJSCoverage(): Promise<JSCoverageEntry[]>;
  startCSSCoverage(options?: CSSCoverageOptions): Promise<void>;
  stopCSSCoverage(): Promise<CSSCoverageEntry[]>;
}

interface Tracing {
  start(options?: TracingOptions): Promise<void>;
  stop(): Promise<Buffer>;
}

interface Accessibility {
  snapshot(options?: SnapshotOptions): Promise<SerializedAXNode | null>;
}

interface JSCoverageOptions {
  resetOnNavigation?: boolean;
  reportAnonymousScripts?: boolean;
  includeRawScriptCoverage?: boolean;
  useBlockCoverage?: boolean;
}

interface CSSCoverageOptions {
  resetOnNavigation?: boolean;
}

interface TracingOptions {
  path?: string;
  screenshots?: boolean;
  categories?: string[];
}

interface SnapshotOptions {
  interestingOnly?: boolean;
  root?: ElementHandle;
}

Usage Examples:

// Code coverage
await page.coverage.startJSCoverage();
await page.goto("https://example.com");
const jsCoverage = await page.coverage.stopJSCoverage();

// Performance tracing
await page.tracing.start({ path: "trace.json" });
await page.goto("https://example.com");
await page.tracing.stop();

// Accessibility tree
const snapshot = await page.accessibility.snapshot();
console.log(JSON.stringify(snapshot, null, 2));

Install with Tessl CLI

npx tessl i tessl/npm-puppeteer-core

docs

browser-contexts.md

browser-management.md

element-handling.md

index.md

input-simulation.md

locators-selectors.md

network-management.md

page-interaction.md

tile.json