Skip to content

context.addInitScript is not applied on new pages #1628

Closed

Description

@theoephraim

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();

Activity

  1. theoephraim commented on Jan 29, 2026

    @theoephraim
    Author

    Was able to work around this for now by adding a hacky new page "hook"

    export function addStagehandNewPageHook(
      stagehand: Stagehand,
      onNewPageFn: (page: Page) => Promise<void>,
    ) {
      // Patch context.onAttachedToTarget to hook into new top-level page creation
      type ContextWithInternals = {
        onAttachedToTarget: (
          info: { targetId: string; type: string; subtype?: string },
          sessionId: string,
        ) => Promise<void>;
        pagesByTarget: Map<string, Page>;
      };
      const stagehandCtx = stagehand.context as unknown as ContextWithInternals;
      const originalOnAttachedToTarget = stagehandCtx.onAttachedToTarget.bind(stagehandCtx);
      stagehandCtx.onAttachedToTarget = async (info, sessionId) => {
        await originalOnAttachedToTarget(info, sessionId);
        const isTopLevel = info.type === 'page' && info.subtype !== 'iframe';
        if (isTopLevel) {
          const newPage = stagehandCtx.pagesByTarget.get(info.targetId);
          if (newPage) {
            await onNewPageFn(newPage);
          }
        }
      };
    }

    And then calling page.evaluate to run some code within my hook function

  2. theoephraim commented on Feb 2, 2026

    @theoephraim
    Author

    Great :)

    A generic new page hook would still be very useful.

  3. added a commit that references this issue on Feb 2, 2026
    3673369
  4. seanmcguire12 commented on Feb 3, 2026

    @seanmcguire12
    Member

    @theoephraim would you mind opening an issue for this? thank you & really appreciate all the detailed issues you've been opening 🙏

  5. added a commit that references this issue on Aug 4, 2026
    e3a22b0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions