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

Use the Puppeteer API that matches your goal: page.addScriptTag() inserts a real <script> element, page.evaluate() runs a function immediately in the page context, and page.evaluateOnNewDocument() installs setup before the page’s own scripts run. For an iframe, call the same method on the relevant Frame object.

Choose the right Puppeteer API

“Add a custom script” can mean three different operations. Decide whether you need a persistent script element, a one-time action, or code that runs before site JavaScript:

API What it does When it runs Typical use
page.addScriptTag() Appends a <script> element to the main-frame document When you call it in the current document Load a local file, inline code, or a browser-loadable URL
page.evaluate() Evaluates a function in the page’s JavaScript context; it does not add a script element Immediately when the evaluation is dispatched Read or change the DOM, call a page function, or perform a one-off action
page.evaluateOnNewDocument() Registers code for each new document After document creation but before that document’s scripts Install globals or browser-environment overrides before application code starts

Page methods target the main frame. To work in a child frame, obtain its Frame and use the corresponding frame method.

Insert a script element with page.addScriptTag()

addScriptTag() accepts a local path, inline content, or remote url. It resolves to an element handle for the injected script, so you can inspect the resulting element after insertion. The options also include id and type; set type: 'module' for an ES module.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

Load a local JavaScript file

A relative path is resolved from Node.js process.cwd(), not necessarily from the directory containing your source file. Use an absolute path or verify the process working directory when running from a task runner, container, or package script.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();
try {
  const page = await browser.newPage();
  await page.goto('https://example.com', {waitUntil: 'networkidle2'});

  const scriptElement = await page.addScriptTag({
    path: './custom.js',
    id: 'my-custom-script',
  });

  console.log(await scriptElement.evaluate(element => ({
    id: element.id,
    src: element.src,
    type: element.type,
  })));
} finally {
  await browser.close();
}

The await on both navigation and addScriptTag() matters. Without it, later actions can run before the script has been inserted or loaded.

Inject inline JavaScript

Use content when the code is already available in your Node.js program. This creates a script element in the page; it is different from calling evaluate().

await page.addScriptTag({
  content: `
    window.myFlag = true;
    document.documentElement.dataset.automation = 'enabled';
  `,
  id: 'inline-setup',
});

If the inline code throws, the returned promise rejects. Wrap the call in your normal error handling and inspect the browser console when diagnosing page-side exceptions.

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

Load a script by URL

await page.addScriptTag({
  url: 'https://example.com/custom.js',
  type: 'text/javascript',
});

The browser must be able to fetch the URL in the page context, and the target site’s environment must permit that load. A URL being syntactically valid does not guarantee that the remote server is reachable or that the page’s policy will allow it.

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

Use the other addScriptTag() options

  • id: assigns an id to the inserted element, making it easier to find or avoid inserting the same script twice.
  • type: sets the script type. Use module when the file or inline source is an ES module.
  • path, content, and url: choose the source that matches where your code lives. Keep the source choice explicit rather than constructing ambiguous option combinations.

Run one-off code with page.evaluate()

Use evaluate() when you need to execute a function now, not add a persistent <script> node. Puppeteer serializes the function and evaluates it in the browser. Node.js lexical variables and helper functions are not available inside the function unless you pass their values as arguments.

const pageTitle = await page.evaluate(() => document.title);
console.log(pageTitle);

const label = 'Automation test';
await page.evaluate(text => {
  document.body.dataset.testLabel = text;
}, label);

Values passed as arguments are serialized. A promise returned by the page function is awaited, and ordinary returned objects are serialized back to Node.js. If you need to keep an in-page object by reference, use evaluateHandle() instead of expecting a normal return value to remain a live DOM object.

const result = await page.evaluate(async () => {
  const response = await fetch('/api/status');
  return {ok: response.ok, status: response.status};
});
console.log(result);

Because this code runs in the page context, browser globals such as window and document are available there, while Node-only APIs such as fs are not.

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

Run setup before the page’s scripts

Register evaluateOnNewDocument() before navigation when the site’s own scripts must see your setup from the beginning. Puppeteer runs the registered function after a document is created but before that document’s scripts. The registration also applies to child frames when they are attached or navigated.

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

await page.goto('https://example.com', {waitUntil: 'domcontentloaded'});

// Remove the registration when it is no longer needed.
await page.removeScriptToEvaluateOnNewDocument(preloadId);

Calling this API after goto() does not retroactively run the code in the document that already exists. Register it first, then navigate or create a new document.

Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.

Use this API for early document setup, not as a replacement for ordinary post-load DOM work. For a button click, text change, or data read after the page is ready, evaluate() is usually clearer.

Inject into an iframe

page.addScriptTag() is a shortcut for the main frame. It does not automatically insert the script into every iframe. Find the intended frame and call addScriptTag() or evaluate() on that frame.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const frame = page.frames().find(candidate =>
  candidate.url().includes('/widget')
);

if (!frame) {
  throw new Error('Widget frame not found');
}

await frame.addScriptTag({
  content: 'window.widgetReady = true;',
});

const ready = await frame.evaluate(() => window.widgetReady === true);
console.log({ready});

Frame URLs and document structure are site-specific. A frame may not have its final URL immediately after the parent navigation, so locate it after the relevant frame navigation or wait for a selector that identifies the embedded content. If the frame is cross-origin, use Puppeteer’s frame execution APIs rather than trying to access its DOM through a parent-frame evaluation.

A complete, ordered workflow

  1. Launch and create a page. Keep the browser in a try/finally block so it closes on failures.
  2. Register pre-document code first. Call evaluateOnNewDocument() before goto() if timing is important.
  3. Navigate and wait for the state your script needs. Select a navigation condition appropriate to the site instead of assuming that the first response means the UI is ready.
  4. Choose the execution method. Use addScriptTag() for a script element, evaluate() for a one-off function, or a frame method for an iframe.
  5. Await every asynchronous operation. This includes navigation, script insertion, evaluations, waits, and frame discovery.
  6. Verify the result in the same context. Read a flag, attribute, or DOM change with evaluate() so a successful promise also corresponds to the expected page state.
import puppeteer from 'puppeteer';

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

  await page.evaluateOnNewDocument(() => {
    window.__customSetup = true;
  });

  await page.goto('https://example.com', {waitUntil: 'domcontentloaded'});

  await page.addScriptTag({
    content: `window.customScriptLoaded = true;`,
    id: 'custom-script',
  });

  const state = await page.evaluate(() => ({
    setup: window.__customSetup === true,
    script: window.customScriptLoaded === true,
    title: document.title,
  }));

  console.log(state);
} finally {
  await browser.close();
}

Troubleshooting custom script injection

The local file cannot be found

Cause: A relative path is resolved from process.cwd(). Fix: log process.cwd(), start the process from the expected directory, or pass an absolute path. Confirm that the file is readable before launching the browser.

The code runs too late

Cause: addScriptTag() or evaluate() was called after the application had already executed the behavior you needed to influence. Fix: register evaluateOnNewDocument() before goto(), then create a new document.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

The function cannot see a Node.js variable

Cause: evaluate() runs in the page context and does not close over Node.js lexical scope. Fix: pass serializable values as arguments, or expose a deliberate bridge rather than referencing the outer variable directly.

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

The script URL does not load

Cause: The browser cannot reach the URL, the remote server rejects the request, or the page’s environment prevents the load. Fix: open the URL in the same page context, inspect browser console/network output, and prefer content or a local path when you control the source.

The script appears in the wrong document

Cause: The operation targeted the main frame while the code you are inspecting lives in an iframe. Fix: enumerate page.frames(), identify the intended frame, and call frame.addScriptTag() or frame.evaluate().

A later step sees old state

Cause: A promise was not awaited, or the page navigated after injection and replaced the document. Fix: await the insertion and any navigation, then verify the state after the final navigation.

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

Version and reliability notes

The referenced Puppeteer API material identifies addScriptTag() options in the 25.10.0 documentation and the Page class in 25.12.0 documentation; the execution and pre-document references use the “next” documentation path. Match these examples to the Puppeteer version installed in your project because APIs can change.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

For repeatable automation, keep injection close to the navigation it belongs to, give each injected element an identifiable id, and make setup functions safe to run on every new document. A page reload creates a new document, so a script element inserted into the old document does not persist unless you register equivalent setup with evaluateOnNewDocument() or inject again.

Or skip the browser setup

If your actual goal is to obtain a clean screenshot rather than execute custom JavaScript in a live Puppeteer session, ScreenshotNeo provides a single HTTP request. Its API accepts a URL and returns PNG, JPEG, WebP, or PDF output; the documentation is at screenshotneo.com/docs/.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each cleanup step can be disabled. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and each response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. The Free plan includes 1,000 screenshots per month without a card; paid plans start at $5 for 3,000 screenshots.

Create a free ScreenshotNeo account to try the 1,000 monthly screenshots without a card.

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

Frequently Asked Questions

Does adding a script survive a page reload?

No. A script element belongs to the current document. Inject it again after the reload, or register equivalent setup with evaluateOnNewDocument() before the next navigation.

Can I add an ES module with Puppeteer?

Yes. Pass type: 'module' along with the script’s path, content, or url.

How can I confirm which frame received my code?

Inspect the frame’s URL and evaluate a marker in that same frame, such as frame.evaluate(() => window.widgetReady), rather than checking only the parent page.

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.