Skip to content

Commit

Permalink
auto delete ctx (#253)
Browse files Browse the repository at this point in the history
* cleanup function

* changeset

* update readme with close

* close() return type

* update changeset
  • Loading branch information
sameelarif authored Dec 3, 2024
1 parent a855e1f commit 598cae2
Show file tree
Hide file tree
Showing 5 changed files with 36 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-chairs-boil.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@browserbasehq/stagehand": minor
---

clean up contexts after use
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ const contributor = await stagehand.extract({
url: z.string(),
}),
});
await stagehand.close();
console.log(`Our favorite contributor is ${contributor.username}`);
```

Expand Down Expand Up @@ -297,6 +298,15 @@ If you are looking for a specific element, you can also pass in an instruction t
const actions = await stagehand.observe();
```

#### `close()`

`close()` is a cleanup method to remove the temporary files created by Stagehand. It's highly recommended that you call this when you're done with your automation.

- **Example:**
```javascript
await stagehand.close();
```

#### `page` and `context`

`page` and `context` are instances of Playwright's `Page` and `BrowserContext` respectively. Use these methods to interact with the Playwright instance that Stagehand is using. Most commonly, you'll use `page.goto()` to navigate to a URL.
Expand Down
3 changes: 3 additions & 0 deletions examples/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ async function example() {
url: z.string(),
}),
});

console.log(`Our favorite contributor is ${contributor.username}`);

await stagehand.close();
}

(async () => {
Expand Down
20 changes: 17 additions & 3 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ async function getBrowser(
},
});

const tmpDirPath = path.join(os.tmpdir(), "ctx_");
const tmpDirPath = path.join(os.tmpdir(), "stagehand");
if (!fs.existsSync(tmpDirPath)) {
fs.mkdirSync(tmpDirPath, { recursive: true });
}
Expand Down Expand Up @@ -250,7 +250,7 @@ async function getBrowser(

await applyStealthScripts(context);

return { context };
return { context, contextPath: tmpDir };
}
}

Expand Down Expand Up @@ -309,6 +309,7 @@ export class Stagehand {
private enableCaching: boolean;
private variables: { [key: string]: any };
private browserbaseResumeSessionID?: string;
private contextPath?: string;

private actHandler?: StagehandActHandler;
private extractHandler?: StagehandExtractHandler;
Expand Down Expand Up @@ -364,7 +365,7 @@ export class Stagehand {
const llmClient = modelName
? this.llmProvider.getClient(modelName, modelClientOptions)
: this.llmClient;
const { context, debugUrl, sessionUrl } = await getBrowser(
const { context, debugUrl, sessionUrl, contextPath } = await getBrowser(
this.apiKey,
this.projectId,
this.env,
Expand All @@ -380,6 +381,7 @@ export class Stagehand {
sessionUrl: undefined,
} as BrowserResult;
});
this.contextPath = contextPath;
this.context = context;
this.page = context.pages()[0];
// Redundant but needed for users who are re-connecting to a previously-created session
Expand Down Expand Up @@ -877,6 +879,18 @@ export class Stagehand {
throw e;
});
}

async close(): Promise<void> {
await this.context.close();

if (this.contextPath) {
try {
fs.rmSync(this.contextPath, { recursive: true, force: true });
} catch (e) {
console.error("Error deleting context directory:", e);
}
}
}
}

export * from "../types/browser";
Expand Down
1 change: 1 addition & 0 deletions types/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export interface BrowserResult {
context: BrowserContext;
debugUrl?: string;
sessionUrl?: string;
contextPath?: string;
}

0 comments on commit 598cae2

Please sign in to comment.