Skip to content

Commit 3d803b4

Browse files
authored
Update playwright.mdx
add new session reuse section
1 parent b1cb01b commit 3d803b4

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

src/content/docs/browser-rendering/platform/playwright.mdx

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,6 +191,29 @@ const browser = await playwright.launch(env.MYBROWSER, { keep_alive: 600000 });
191191

192192
Using the above, the browser will stay open for up to 10 minutes, even if inactive.
193193

194+
### Session Reuse
195+
196+
The best way to improve the performance of your browser rendering Worker is to reuse sessions by keeping the browser open after you've finished with it, and connecting to that session each time you have a new request. Playwright handles [`browser.close`](https://playwright.dev/docs/api/class-browser#browser-close) differently from Puppeteer. In Playwright, if the browser was obtained using a `connect` session, the session will disconnect. If the browser was obtained using a `launch` session, the session will close.
197+
198+
```js
199+
import { env } from "cloudflare:workers";
200+
import { acquire, connect } from "@cloudflare/playwright";
201+
202+
async function reuseSameSession() {
203+
// acquires a new session
204+
const { sessionId } = await acquire(env.BROWSER);
205+
206+
for (let i = 0; i < 5; i++) {
207+
// connects to the session that was previously acquired
208+
const browser = await connect(env.BROWSER, sessionId);
209+
210+
// ...
211+
212+
await browser.close();
213+
}
214+
}
215+
```
216+
194217
### Set a custom user agent
195218

196219
To specify a custom user agent in Playwright, set it in the options when creating a new browser context with `browser.newContext()`. All pages subsequently created from this context will use the new user agent. This is useful if the target website serves different content based on the user agent.

0 commit comments

Comments
 (0)