What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
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:
Recommended Free Tools
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.
#1 Best Overall
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
- 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.
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:
Rank #3
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
- 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.
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.
Best Value
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.
Do these 3 things before closing this tab:
1Repair Windows errors before they cause bigger problems2Scan for outdated or missing drivers - takes under a minute3Clear out junk files and repair common Windows errorsTarget 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 callingpage.goto(). - The script file cannot be found. Check the path and remember that a relative
pathis resolved fromprocess.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.
Quick Recap
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.




