Skip to content

Commit e9d5692

Browse files
Add: initFromPage method to Stagehand to support external Page objects (#152)
* Update index.ts * Update index.ts * Update index.ts
1 parent 3e37495 commit e9d5692

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

lib/index.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,43 @@ export class Stagehand {
270270
return { debugUrl, sessionUrl };
271271
}
272272

273+
async initFromPage(
274+
page: Page,
275+
modelName?: AvailableModel,
276+
): Promise<{ context: BrowserContext }> {
277+
this.page = page;
278+
this.context = page.context();
279+
this.defaultModelName = modelName || this.defaultModelName;
280+
281+
const originalGoto = this.page.goto.bind(this.page);
282+
this.page.goto = async (url: string, options?: any) => {
283+
const result = await originalGoto(url, options);
284+
await this.page.waitForLoadState("domcontentloaded");
285+
await this._waitForSettledDom();
286+
return result;
287+
};
288+
289+
// Set the browser to headless mode if specified
290+
if (this.headless) {
291+
await this.page.setViewportSize({ width: 1280, height: 720 });
292+
}
293+
294+
// Add initialization scripts
295+
await this.page.addInitScript({
296+
path: path.join(__dirname, "..", "dist", "dom", "build", "process.js"),
297+
});
298+
299+
await this.page.addInitScript({
300+
path: path.join(__dirname, "..", "dist", "dom", "build", "utils.js"),
301+
});
302+
303+
await this.page.addInitScript({
304+
path: path.join(__dirname, "..", "dist", "dom", "build", "debug.js"),
305+
});
306+
307+
return { context: this.context };
308+
}
309+
273310
// Logging
274311
private pending_logs_to_send_to_browserbase: {
275312
category?: string;

0 commit comments

Comments
 (0)