This example sandbox template shows how to run Playwright inside an E2B sandbox.
This project contains a ready-to-use example of running Playwright in an E2B sandbox.
-
Copy the environment variables file and add your API keys:
cp example.env .env
-
Edit the
.envfile and add your API keys:# Fill in your E2B API key and OpenAI API key here # You can get your E2B API key from https://e2b.dev/dashboard # You can get your OpenAI API key from https://platform.openai.com/account/api-keys E2B_API_KEY=your_e2b_api_key_here OPENAI_API_KEY=your_openai_api_key_here -
Edit the
script.mjsfile to contain your Playwright script:import { chromium } from 'playwright' const browser = await chromium.launch() const context = await browser.newContext() const page = await context.newPage() await page.goto('https://playwright.dev/'); await page.screenshot({ path: '/home/user/example.png' }); await browser.close() console.log('done')
-
Install dependencies and run the example:
npm install npm run start
The example will:
- Create a new E2B sandbox with Playwright pre-installed
- Run the Playwright script
- Copy output files to the
outputdirectory - Clean up the sandbox
You can find the complete example code in the app.ts file.
To run Playwright scripts via the E2B SDK:
import { Sandbox } from 'e2b'
const sbx = await Sandbox.create('playwright-chromium')
// Run the command verifying that Playwright is installed
const result = await sbx.commands.run('PLAYWRIGHT_BROWSERS_PATH=0 npx playwright --version', {
cwd: '/app' // Important: Commands must run from the /app directory
})
console.log(result.stdout)
await sbx.kill()Important
All Playwright scripts must be run from the /app directory, as this is where the Playwright browsers are installed and configured.
Important
The environment variable PLAYWRIGHT_BROWSERS_PATH=0 is necessary to tell Playwright to look for browser binaries in the current Node.js project directory.
- Run
npm i -g @e2b/cli@latestto install the latest version of the E2B CLI. - Run
e2b template initin your project directory. - Copy the e2b.Dockerfile into your project.
- Run
e2b template buildto build your sandbox. - Start the sandbox either via our SDK or the E2B CLI like this
e2b sandbox spawn <sandbox-template-id>.
Warning
This template only works with the node:20-slim base image as shown in the Dockerfile. It is not compatible with the e2bdev/code-interpreter base image due to specific dependencies required for Playwright.