DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
World desk4 min

How to Run JavaScript Before a Page Loads in Puppeteer

Register page.evaluateOnNewDocument() before navigation to run JavaScript after document creation but before the page’s own scripts.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use page.evaluateOnNewDocument() and register the function before calling page.goto(). Puppeteer runs it after the new document is created but before that document’s scripts, so it is the right hook for setting page-visible values before site code executes.

Register code before navigating

Here is a complete minimal example using Puppeteer. The script sets navigator.languages in each newly created document before the page’s own scripts run:

As an Amazon Associate I earn from qualifying purchases.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();

    await page.evaluateOnNewDocument(() => {
      Object.defineProperty(navigator, 'languages', {
        get: () => ['en-US', 'en'],
      });
    });

    const response = await page.goto('https://example.com');
    console.log('HTTP status:', response?.status() ?? 'no main-resource response');
  } finally {
    await browser.close();
  }
})();

The order matters: create or obtain the Page, register the new-document script, then navigate to the URL of interest. If navigation has already happened, registering the hook does not retroactively run it in that existing document.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What runs when, and where

page.evaluateOnNewDocument(fn, ...args) registers a function or string for future document creation. It runs after the document is created but before its scripts, including on navigation and when child frames attach or navigate. This timing makes it suitable for initialization that the site’s own JavaScript must see from its earliest execution.

It is not the same as evaluating code in the page that is already open, or adding a script element:

Need API Timing and scope
Run setup before scripts in newly created documents page.evaluateOnNewDocument(fn, ...args) Registered for navigations and child-frame attach/navigation.
Run code in the current page context page.evaluate(fn, ...args) Executes when called in the current page context; it is not the document-start registration hook.
Insert a script element page.addScriptTag({ content }) or a URL option Adds a <script> element; the API describes this as a shortcut for the main frame.

Pass data from Node.js explicitly

Puppeteer serializes the function supplied for page-context execution. It does not carry over the Node.js caller’s lexical variables or functions. Pass values as arguments instead, and keep browser-side code self-contained.

const languageList = ['en-US', 'en'];

await page.evaluateOnNewDocument((languages) => {
  Object.defineProperty(navigator, 'languages', {
    get: () => languages,
  });
}, languageList);

await page.goto('https://example.com');

Page-context return values are serialized. If you need to retain a DOM object by reference, use a handle rather than expecting the object itself to cross back to Node.js as a live object.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Frames, navigation, and removing the hook

Frame coverage

Puppeteer documents the new-document callback as running on navigation and when child frames attach or navigate. However, evaluation in one frame does not affect nested child frames. Do not assume a main-frame operation changes every nested frame; for iframe-heavy pages, verify the frame behavior the task requires.

Remove a registered script

evaluateOnNewDocument() returns a NewDocumentScriptEvaluation that includes an identifier. Keep that identifier if you may need to stop injecting the script:

const registration = await page.evaluateOnNewDocument(() => {
  // New-document setup
});

// Later, stop injecting this registered script.
await page.removeScriptToEvaluateOnNewDocument(registration.identifier);

Removing the registration prevents its future injection; it is not a way to undo changes already made in a document.

Navigation response and waiting behavior

page.goto(url) navigates to the requested URL and accepts options that control when its navigation wait resolves. It returns the main resource response, or null for about:blank and same-URL hash navigation. The example uses optional chaining because a response is not guaranteed for those cases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting

  • The site’s first script sees the original value. Register the hook before the navigation that creates the document. A call made after goto() is too late for that document.
  • A Node.js variable is undefined in the callback. The callback is serialized for the page context and cannot close over Node.js lexical scope. Pass the needed value through ...args.
  • An iframe does not show the change. A frame’s evaluation does not alter nested child frames. Check which frame is being initialized and verify the target iframe’s own attach/navigation behavior.
  • You expected a return value or live DOM node. Page-context values are serialized; use a handle when you need a DOM object by reference.
  • goto() produced no response. A null main-resource response is documented for about:blank and same-URL hash navigation. Do not treat that return value alone as proof that a normal document request failed.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a screenshot rather than running custom browser-side code, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns an image or PDF. It does not replace Puppeteer’s programmable page context, but it can avoid setting up a browser for capture workflows.

For example, this cURL call saves a WebP screenshot of the target URL; see the ScreenshotNeo API documentation for request options:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com -o shot.webp
  • Cookie banners are accepted and removed before capture, along with supported newsletter popups and chat widgets.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed.
  • An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for AI agents.
  • The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots.

Sign up for ScreenshotNeo’s free plan to try it with 1,000 screenshots a month and no card.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.