October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk5 min

How to Add Custom JavaScript to a Page with Puppeteer

Use Puppeteer’s addScriptTag to insert JavaScript, evaluate to run a page-context function, or evaluateOnNewDocument to set up code before page scripts.

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.

Choose the Puppeteer method that matches when and how you want the code to run: use page.addScriptTag() to insert a script element, page.evaluate() to run a function in the current page and retrieve its result, or page.evaluateOnNewDocument() to run setup code before a document’s own scripts. The examples below use Puppeteer’s JavaScript API.

Choose the right injection method

Method Use it when Timing and result
page.addScriptTag() You want to add inline code or load a script from a URL or local path. Inserts a <script> into the page’s main frame and returns an element handle.
page.evaluate() You need to perform a page-context operation or read a value. Runs a function in the current page and returns its serializable result; Puppeteer waits if the function returns a Promise.
page.evaluateOnNewDocument() You must set up page state before the website’s scripts execute. Registers a function to run after each new document is created but before its scripts run.

These methods solve different problems. Inserting a script leaves a script element in the document; evaluating a function is a direct execution; registering a new-document function establishes code for future documents. None guarantees that a particular website will allow or behave as expected with injected code.

As an Amazon Associate I earn from qualifying purchases.

Set up a Puppeteer page

Install Puppeteer in a Node.js project if it is not already installed, then launch a browser and create a page. This complete example uses Puppeteer’s bundled browser:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  try {
    const page = await browser.newPage();
    await page.goto('https://example.test', { waitUntil: 'domcontentloaded' });

    await page.addScriptTag({ content: 'window.myFlag = true;' });
    const flag = await page.evaluate(() => window.myFlag);
    console.log(flag); // true
  } finally {
    await browser.close();
  }
})();

Replace https://example.test with the page you control or are authorized to automate. The snippets in the following sections can be used in place of the insertion and evaluation lines.

Insert JavaScript as a script element

Inline code

Pass a string as content when you want the code inserted into the document as a script:

await page.addScriptTag({
  content: `window.myFlag = true;`,
});

The method returns a handle to the inserted script element. You can retain that handle if you need to inspect or interact with the element later.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option

Load a remote script

Pass the script URL as url:

await page.addScriptTag({
  url: 'https://example.test/custom.js',
});

The remote file must be reachable from the browser page. Whether it loads successfully depends on the target page and its security or network controls.

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

Load a local file or module

Use path for a local JavaScript file. Relative paths resolve from the Node.js process working directory, process.cwd(). Set type: 'module' when the script is an ES module:

await page.addScriptTag({ path: './scripts/custom.js' });

await page.addScriptTag({
  path: './scripts/custom-module.js',
  type: 'module',
});

The documented options include content, url, path, and type. Use an appropriate source option for the script; page.addScriptTag() is a shortcut for adding a script tag to the main frame.

Run a function and get its result

Use page.evaluate() when you do not need to insert a script element. The function runs in the page’s JavaScript context, so browser objects such as document are available there:

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
const title = await page.evaluate(() => document.title);
console.log(title);

Pass values after the function rather than closing over Node.js variables: the function runs in the browser context, not the Node.js context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const selector = '#status';
const text = await page.evaluate((css) => {
  return document.querySelector(css)?.textContent ?? null;
}, selector);

If the function returns a Promise, Puppeteer waits for it to resolve before returning the result to Node.js. Use a value that can be transferred back from the page context, such as a string, number, boolean, array, or plain object.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run setup code before the website’s scripts

Register the function before navigation when it must run on a newly created document before that document’s own scripts:

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

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

The registered function runs when the page navigates to a new document. It also runs when a child frame is attached or navigated. Puppeteer returns an identifier for the registration; retain it if you may want to remove the setup later:

await page.removeScriptToEvaluateOnNewDocument(registrationId);

Registering after a page has already loaded does not retroactively run the setup in that existing document. Register before the navigation that creates the document you want to affect.

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

Target the correct frame

A page can contain iframes, each with its own JavaScript context. page.addScriptTag() targets the main frame; code evaluated in one frame does not automatically affect nested frames. For an iframe, identify its frame and use the relevant frame-level method or evaluate in that frame’s context. The new-document registration is the exception in scope: Puppeteer documents that it also runs for child frames when they are attached or navigated.

Common problems and fixes

  • The code cannot see a Node.js variable. Functions passed to page.evaluate() run in the browser, not Node.js. Pass required values as arguments after the function.
  • The code runs too late. If the page’s own scripts must not run first, register with page.evaluateOnNewDocument() before calling page.goto().
  • The script file cannot be found. Check the path and remember that a relative path is resolved from process.cwd(), which may differ from the script file’s directory.
  • The script URL fails to load. Verify the URL is reachable from the browser and check the page’s security policies and network conditions. Puppeteer’s API does not establish that every target will accept an injected script.
  • The change does not appear inside an iframe. The main-frame context and iframe contexts are separate. Select the intended frame and execute the operation there.
  • The setup runs on later navigations as well. That is expected for a new-document registration. Save its identifier and call page.removeScriptToEvaluateOnNewDocument() when you no longer want it registered.

Or skip the browser setup

If your goal is a website screenshot rather than custom browser-side behavior, ScreenshotNeo returns an image or PDF from one GET request. It does not run arbitrary custom JavaScript as a Puppeteer replacement. Its screenshot workflow accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, with the outcome identified in response headers. It also provides an MCP server for AI agents and supports PNG, JPEG, WebP, or PDF output. See the API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.test -o shot.webp

The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Sign up for free.

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.

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
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

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.