From e9d56921e62d79949c7c43bb2f50afa3ae24c766 Mon Sep 17 00:00:00 2001 From: Chinmay Shrivastava <79005030+ChinmayShrivastava@users.noreply.github.com> Date: Fri, 1 Nov 2024 01:03:05 -0400 Subject: [PATCH] Add: initFromPage method to Stagehand to support external Page objects (#152) * Update index.ts * Update index.ts * Update index.ts --- lib/index.ts | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/lib/index.ts b/lib/index.ts index 7dce2730..0ae8131f 100644 --- a/lib/index.ts +++ b/lib/index.ts @@ -270,6 +270,43 @@ export class Stagehand { return { debugUrl, sessionUrl }; } + async initFromPage( + page: Page, + modelName?: AvailableModel, + ): Promise<{ context: BrowserContext }> { + this.page = page; + this.context = page.context(); + this.defaultModelName = modelName || this.defaultModelName; + + const originalGoto = this.page.goto.bind(this.page); + this.page.goto = async (url: string, options?: any) => { + const result = await originalGoto(url, options); + await this.page.waitForLoadState("domcontentloaded"); + await this._waitForSettledDom(); + return result; + }; + + // Set the browser to headless mode if specified + if (this.headless) { + await this.page.setViewportSize({ width: 1280, height: 720 }); + } + + // Add initialization scripts + await this.page.addInitScript({ + path: path.join(__dirname, "..", "dist", "dom", "build", "process.js"), + }); + + await this.page.addInitScript({ + path: path.join(__dirname, "..", "dist", "dom", "build", "utils.js"), + }); + + await this.page.addInitScript({ + path: path.join(__dirname, "..", "dist", "dom", "build", "debug.js"), + }); + + return { context: this.context }; + } + // Logging private pending_logs_to_send_to_browserbase: { category?: string;