Repository navigation
Closed
Description
Environment Information
Please provide the following information to help us reproduce and resolve your issue:
Stagehand:
- Language/SDK: TypeScript
- Stagehand version: 3.0.8
Issue Description
Using context.addInitScript I expected that the script would be injected on every new page that is opened.
The docs say:
Automatically applies the same script to any pages created after calling context.addInitScript()
It appears this is not the case. Does not matter if the page was opened via clicking within an existing tab or via newPage()
Minimal repro
import { setTimeout as delay } from 'node:timers/promises';
import { Stagehand } from '@browserbasehq/stagehand';
const stagehand = new Stagehand({ env: 'LOCAL' });
await stagehand.init();
let page = stagehand.context.pages()[0];
if (!page) throw new Error('Expected browser page');
// Define the HTML we'll serve
const html = `
<!DOCTYPE html>
<html><head><title>Init script test</title>
</head><body id="body">
<h2>Testing contxt.addInitScript</h2>
<p><b>Page background should be red!</b></p>
<p>
<a href="/" target="_blank">Open another tab</a>
</p>
</body></html>
`;
const port = 6789;
const localhostUrl = `http://127.0.0.1:${port}/`;
const server = Bun.serve({
port,
fetch(req) {
return new Response(html, { headers: { "Content-Type": "text/html" }});
}
});
console.log(`Test server running at ${localhostUrl}`);
// use context.addInitScript - it should run on _every_ page
await stagehand.context.addInitScript(`
(() => {
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('body').style.backgroundColor = 'red';
});
})();
`);
// navigate in the initial page
await page.goto(localhostUrl);
await delay(1000);
// open a new page via clicking
await page.locator('a').click();
await delay(1000);
// open another via newPage()
await stagehand.context.newPage(localhostUrl);
await delay(1000);
await stagehand.close();
await server.stop();
Metadata
Metadata
Assignees
Labels
No labels
Activity
theoephraim commentedon Jan 29, 2026
Was able to work around this for now by adding a hacky new page "hook"
And then calling
page.evaluateto run some code within my hook functiontheoephraim commentedon Feb 2, 2026
Great :)
A generic new page hook would still be very useful.
[fix]: ctx `addInitScript` on popup pages (browserbase#1642)
seanmcguire12 commentedon Feb 3, 2026
@theoephraim would you mind opening an issue for this? thank you & really appreciate all the detailed issues you've been opening 🙏
[fix]: ctx `addInitScript` on popup pages (browserbase#1642)