A screenshot taken with Browserbase can be saved locally as a file:
import{ writeFileSync }from"fs";import{ chromium }from"playwright-core";(async()=>{console.log("Starting remote browser...")const browser =await chromium.connectOverCDP(// we connect to a Session created via the API`wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}&sessionId=${sessionId}`,);const defaultContext = browser.contexts()[0];const page = defaultContext.pages()[0];await page.goto("https://www.browserbase.com",{// let's make sure the page is fully loaded before taking the screenshot waitUntil:"domcontentloaded",});console.log("Taking a screenshot!")const buf =await page.screenshot({ fullPage:true})writeFileSync('screenshot.jpeg', buf)console.log("Shutting down...")await page.close();await browser.close();})().catch((error)=>{console.error(error)}
Here’s how to generate and save a PDF locally using Playwright:
Playwright
import{ chromium }from"playwright-core";(async()=>{console.log("Starting remote browser...");// we connect to a Session created via the APIconst browser =await chromium.connectOverCDP(`wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}`,);const defaultContext = browser.contexts()[0];const page = defaultContext.pages()[0];await page.goto("https://www.browserbase.com",{// let's make sure the page is fully loaded before taking the screenshot waitUntil:"domcontentloaded",});console.log("Generating PDF...");await page.pdf({ path:"webpage.pdf", format:"A4",});console.log("Shutting down...");await page.close();await browser.close();})().catch((error)=>{console.error(error);});
Unlike screenshots and PDFs which are saved locally, files downloaded during browser automation are stored in Browserbase’s cloud storage. These files must be retrieved using our API.
A typical use case for headless browsers is downloading files from
web pages. Our browsers are configured to sync any file you download to our
storage infrastructure. We add a Unix timestamp onto the end of the file name to avoid naming conflicts when downloading multiple files (e.g., sample.pdf will become sample-1719265797164.pdf).
Follow these steps to download files:
Use the
Sessions API
to create a new session. You’ll need the session ID for when you connect.
Configure your library’s downloads location.
Perform the download action in your automation script.
import{ chromium }from"playwright-core";import{ writeFileSync }from"node:fs";asyncfunctionsaveDownloadsOnDisk(sessionId:string, retryForSeconds:number){returnnewPromise<void>((resolve, reject)=>{let pooler;const timeout =setTimeout(()=>{if(pooler){clearInterval(pooler);}}, retryForSeconds);asyncfunctionfetchDownloads(){try{const response =awaitfetch(`https://api.browserbase.com/v1/sessions/${sessionId}/downloads`,{ method:"GET", headers:{"x-bb-api-key": process.env.BROWSERBASE_API_KEY!,},},);const arrayBuffer =await response.arrayBuffer();if(arrayBuffer.byteLength >0){const buffer = Buffer.from(arrayBuffer);writeFileSync("downloads.zip", buffer);clearInterval(pooler);clearTimeout(timeout);resolve();}}catch(e){clearInterval(pooler);clearTimeout(timeout);reject(e);}} pooler =setInterval(fetchDownloads,2000);});}(async()=>{// `createSession()` performs a call to the Sessions APIconst{ id: sessionId }=awaitcreateSession();const browser =await chromium.connectOverCDP(// we connect to a Session created via the API`wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}&sessionId=${sessionId}`,);const defaultContext = browser.contexts()[0];const page = defaultContext.pages()[0];// Required to avoid playwright overriding locationconst client =await defaultContext.newCDPSession(page);await client.send("Browser.setDownloadBehavior",{ behavior:"allow", downloadPath:"downloads", eventsEnabled:true,});await page.goto("https://browser-tests-alpha.vercel.app/api/download-test");const[download]=awaitPromise.all([ page.waitForEvent("download"), page.locator("#download").click(),]);let downloadError =await download.failure();if(downloadError !==null){console.log("Error happened on download:", downloadError);thrownewError(downloadError);}await page.close();await browser.close();if(!downloadError){// wait up to 20s to save the downloaded files locallyawaitsaveDownloadsOnDisk(sessionId,20000);}})().catch((error)=>console.error(error.message));
We sync the files in real-time; the size of your downloads might affect their
immediate availability through the /downloads endpoint. The above code
provides a snippet to handle that use case.
For Playwright, you can upload files directly from your local path.
You’ll need your file to be available where you’re running your Playwright code.
In this example, we’re using an image logo.png that’s available locally.
Be sure to specify the path to your file by setting the input file.
import{ chromium }from"playwright-core";(async()=>{const url ="https://browser-tests-alpha.vercel.app/api/upload-test";const browser =await chromium.connectOverCDP(`wss://connect.browserbase.com?apiKey=${process.env.BROWSERBASE_API_KEY}`,);const defaultContext = browser.contexts()[0];const page = defaultContext.pages()[0];await page.goto(url);const fileInput = page.locator("#fileUpload");// logo.png is available relative to the current working directoryawait fileInput.setInputFiles("logo.png");await browser.close();})().catch((error)=>console.error(error.message));
For Puppeteer and Selenium, you’ll need to upload your files to our browser instance using our Uploads API.
Use the
Sessions API
to create a new session. You’ll need the session ID when you upload it.