### Complete Example: Hybrid BQL with Playwright Source: https://docs.browserless.io/browserql/hybrid-bql Demonstrates initializing a BrowserQL session, connecting Playwright to it, monitoring via LiveURL, performing actions, and capturing screenshots. This example showcases the synergy between BQL and Playwright. ```javascript const playwright = require('playwright-core'); const browserless = require('browserless'); async function run() { const bt = await browserless.create({ token: process.env.BROWSERLESS_TOKEN, }); const page = await bt.page({ // Optionally provide a BQL query, e.g.: // bql: 'select * from html where url = "https://example.com"' }); const liveUrl = await page.url(); console.log('LiveURL:', liveUrl); // Connect Playwright to the existing session const browser = await playwright.connect({ wsEndpoint: liveUrl.replace('http', 'ws') + '/playwright', }); const context = await browser.newContext(); const pPage = await context.newPage(); await pPage.goto('https://example.com'); await pPage.screenshot({ path: 'example-playwright.png' }); await browser.close(); await bt.close(); } ``` -------------------------------- ### Run Browserless Docker Image Source: https://docs.browserless.io/enterprise/docker/quickstart This command starts the Browserless.io Docker container with specified environment variables for concurrency and a custom token. It maps port 3000 and automatically cleans up the container upon exit. Ensure you have Docker installed to run this command. ```bash docker run \ --rm \ -p 3000:3000 \ -e "CONCURRENT=10" \ -e "TOKEN=6R0W53R135510" \ ghcr.io/browserless/chromium ``` -------------------------------- ### Complete Example: Hybrid BQL with Puppeteer Source: https://docs.browserless.io/browserql/hybrid-bql Illustrates initializing a BrowserQL session, connecting Puppeteer to it, monitoring through LiveURL, executing browser actions, and capturing screenshots. This example highlights the integration of BQL and Puppeteer. ```javascript const puppeteer = require('puppeteer-core'); const browserless = require('browserless'); async function run() { const bt = await browserless.create({ token: process.env.BROWSERLESS_TOKEN, }); const page = await bt.page({ // Optionally provide a BQL query, e.g.: // bql: 'select * from html where url = "https://example.com"' }); const liveUrl = await page.url(); console.log('LiveURL:', liveUrl); // Connect Puppeteer to the existing session const browser = await puppeteer.connect({ wsEndpoint: liveUrl.replace('http', 'ws') + '/puppeteer', }); const context = await browser.createIncognitoBrowserContext(); const pPage = await context.newPage(); await pPage.goto('https://example.com'); await pPage.screenshot({ path: 'example-puppeteer.png' }); await browser.close(); await bt.close(); } ``` -------------------------------- ### Install Playwright and Puppeteer Core Packages Source: https://docs.browserless.io/browserql/hybrid-bql Installs the necessary core packages for Playwright and Puppeteer. Ensure you use a version compatible with Browserless. ```bash # For Playwright npm install playwright-core@1.50.1 # For Puppeteer Npm install puppeteer-core ``` -------------------------------- ### Install Laravel Browserless SDK Source: https://docs.browserless.io/baas/libraries/php Installs the 'millerphp/laravel-browserless' package using Composer, enabling the use of Browserless features within a Laravel application. ```bash composer require millerphp/laravel-browserless ``` -------------------------------- ### Connect Playwright to Browserless Source: https://docs.browserless.io/enterprise/docker/quickstart Example of how to configure Playwright to connect to a locally running Browserless instance. This snippet shows initializing Playwright with the appropriate executable path for Browserless. ```javascript const { chromium } = require('playwright-core'); const browser = await chromium.launch({ args: [ '--no-sandbox', '--disable-setuid-sandbox', ], // If you're using Browserless as a service, you can point to it here. // executablePath: 'Chromium.app/Contents/MacOS/Chromium', // For macOS users // executablePath: '/usr/bin/google-chrome-stable', // For Linux users // executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', // For Windows users // OR set the executablePath to the path of the browserless executable: executablePath: process.env.CHROME_PATH, // Set the token directly: // token: process.env.TOKEN, }); const page = await browser.newPage(); await page.goto('https://example.com'); // ... await browser.close(); ``` -------------------------------- ### Debugger Startup Output Source: https://github.com/browserless/browserless Example log output indicating the availability of the Browserless debugger after successful installation and startup. Shows access URLs for documentation and the debugger itself. ```log --------------------------------------------------------- | browserless.io | To read documentation and more, load in your browser: | | OpenAPI: http://localhost:3000/docs | Full Documentation: https://docs.browserless.io/ | Debbuger: http://localhost:3000/debugger/?token=6R0W53R135510 --------------------------------------------------------- ``` -------------------------------- ### Install Browserless Debugger Source: https://github.com/browserless/browserless Instructions for installing the Browserless debugger after building the project. This script setup enables interactive debugging capabilities. ```shell $ npm run build $ npm run install:debugger #or npm install:dev ``` -------------------------------- ### Connect Puppeteer to Browserless Source: https://docs.browserless.io/enterprise/docker/quickstart Example of how to configure Puppeteer to connect to a locally running Browserless instance using the provided token. This snippet demonstrates initializing a browser instance pointing to the Browserless service. ```javascript const puppeteer = require('puppeteer-core'); const browser = await puppeteer.launch({ args: [ '--no-sandbox', '--disable-setuid-sandbox', ], // If you're using Browserless as a service, you can point to it here. // executablePath: 'Chromium.app/Contents/MacOS/Chromium', // For macOS users // executablePath: '/usr/bin/google-chrome-stable', // For Linux users // executablePath: 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', // For Windows users // OR set the executablePath to the path of the browserless executable: executablePath: process.env.CHROME_PATH, // Set the token directly: // token: process.env.TOKEN, }); const page = await browser.newPage(); await page.goto('https://example.com'); // ... await browser.close(); ``` -------------------------------- ### BrowserQL Query Examples Source: https://docs.browserless.io/open-api Examples of BrowserQL queries for various browser automation tasks, including getting browser information, navigating pages, filling forms, and extracting data using selectors. ```graphql query { version browser } ``` ```graphql mutation { goto(url: "https://example.com") { status } title { title } url { url } } ``` ```graphql mutation { goto(url: "https://example.com") { status } type(selector: "input[name='email']", text: "user@example.com") { time } click(selector: "button[type='submit']") { time } } ``` ```graphql mutation { querySelector(selector: "h1") { innerHTML } querySelectorAll(selector: ".product") { innerHTML className } } ``` -------------------------------- ### Capture Screenshot with Playwright (Node.js) Source: https://docs.browserless.io/enterprise/docker/quickstart This example utilizes Playwright to connect to a Browserless instance over CDP (Chrome DevTools Protocol), creates a new context and page, navigates to a URL, waits for 5 seconds, takes a PNG screenshot, and returns it. It requires 'express' and 'playwright' npm packages. ```javascript const express = require('express'); const playwright = require('playwright'); const app = express(); app.get('/image', async (req, res) => { const browser = await playwright.chromium.connectOverCDP('ws://localhost:3000?token=6R0W53R135510'); const context = await browser.newContext(); const page = await context.newPage(); await page.goto('http://www.example.com/'); await new Promise((resolve) => setTimeout(resolve, 5000)); const data = await page.screenshot({ type: 'png' }); await browser.close(); return res.end(data, 'binary'); }); app.listen(8080); ``` -------------------------------- ### Browserless API: Full Session Management and Scraping (JavaScript) Source: https://docs.browserless.io/browserql/connecting-libraries/playwright This JavaScript example shows how to start a session, fetch data using a selector, and refresh the session to maintain its activity. It utilizes the 'node-fetch' library for making HTTP requests. The code defines functions for starting, refreshing, and fetching data, and includes a loop to scrape multiple pages. ```javascript import fetch from 'node-fetch'; const API_KEY = "YOUR_API_TOKEN_HERE"; const BQL_ENDPOINT = `https://production-sfo.browserless.io/chromium/bql?token=${API_KEY}`; const sessionQuery = `mutation StartSession { goto(url: "https://example.com", waitUntil: networkIdle) { status } reconnect(timeout: 60000) { # Keeps session open for 60 seconds browserQLEndpoint } }`; async function startSession() { const response = await fetch(BQL_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: sessionQuery }), }); const data = await response.json(); console.log("Reconnect URL:", data.data.reconnect.browserQLEndpoint); return data.data.reconnect.browserQLEndpoint; } async function fetchData(reconnectUrl) { const scrapeQuery = `mutation FetchData { text(selector: ".product-title") { text } }`; const reconnectUrlWithToken = reconnectUrl + "?token=" + API_KEY; const response = await fetch(reconnectUrlWithToken, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ query: scrapeQuery }), }); const data = await response.json(); console.log("Fetched Data:", data.data.text.text); return data.data.text.text; } async function refreshSession() { const refreshQuery = `mutation RefreshSession { reconnect(timeout: 60000) { # Extends session timeout browserQLEndpoint } }`; const response = await fetch(BQL_ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ query: refreshQuery }), }); const data = await response.json(); console.log("New Reconnect URL:", data.data.reconnect.browserQLEndpoint); return data.data.reconnect.browserQLEndpoint; }(async () => { let reconnectUrl = await startSession(); let pagesScraped = 0; const PAGE_LIMIT = 20; for (let i = 0; i < 100; i++) { if (pagesScraped >= PAGE_LIMIT) { reconnectUrl = await refreshSession(); pagesScraped = 0; } const data = await fetchData(reconnectUrl); console.log(`Scraped Page ${i + 1}:`, data); pagesScraped++; } })(); ``` -------------------------------- ### Java Example Source: https://docs.browserless.io/browserql/writing-bql/exporting-scripts Example of how to use the BrowserQL API with Java to extract job titles and links. ```APIDOC ```java import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.Unirest; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import com.google.gson.JsonObject; import com.google.gson.JsonParser; public class ExtractJobsHTML { public static void main(String[] args) throws Exception { HttpResponse response = Unirest.post("https://production-sfo.browserless.io/chromium/bql?token=YOUR_API_TOKEN_HERE") .body("{\"query\":\"mutation ExtractJobsHTML {\\n goto(url: \\\"https://news.ycombinator.com\\\", waitUntil: firstMeaningfulPaint) {\\n status\\n }\\n \\n click(selector: \\\"span.pagetop > a[href=\\\'jobs\\\']\\\") {\\n x\\n y\\n }\\n \\n html {\\n html\\n }\\n}\",\"variables\":null,\"operationName\":\"ExtractJobsHTML\"}") .asString(); // Parse JSON response JsonObject jsonResponse = JsonParser.parseString(response.getBody()).getAsJsonObject(); String html = jsonResponse.getAsJsonObject("data").getAsJsonObject("html").get("html").getAsString(); // Parse HTML with Jsoup Document doc = Jsoup.parse(html); Elements jobs = doc.select("tr.athing"); for (Element job : jobs) { Element titleTag = job.selectFirst("a"); if (titleTag != null) { System.out.println("Title: " + titleTag.text()); System.out.println("Link: " + titleTag.attr("href")); } } } } ``` ``` -------------------------------- ### Install Browserless Debugger (npm) Source: https://github.com/browserless/browserless Installs the browserless debugger by running the 'install:debugger' script after the project has been built using npm. This process is followed by running the application. ```npm npm run build npm run install:debugger # or npm install:dev ``` -------------------------------- ### Start Browserless.io Session with BQL (C#) Source: https://docs.browserless.io/browserql/connecting-libraries/playwright Initiates a browser session using Browserless.io's BQL API. It sends a GraphQL mutation to navigate to a URL and wait for network idle, then reconnects to get the browser endpoint. Requires an API key and the `System.Net.Http`, `System.Text.Json`, and `System.Threading.Tasks` namespaces. ```csharp using System; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; class Program { private const string ApiKey = "YOUR_API_TOKEN_HERE"; private static readonly string BqlEndpoint = $"https://production-sfo.browserless.io/chromium/bql?token={ApiKey}"; private const string sessionQuery = @" mutation StartSession { goto(url: \"https://example.com\", waitUntil: networkIdle) { status } reconnect(timeout: 60000) { browserQLEndpoint } }"; static async Task Main() { using var client = new HttpClient(); var payload = new { query = sessionQuery }; var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json"); var response = await client.PostAsync(BqlEndpoint, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); using var doc = JsonDocument.Parse(responseBody); var endpoint = doc.RootElement.GetProperty("data") .GetProperty("reconnect") .GetProperty("browserQLEndpoint") .GetString(); Console.WriteLine("Reconnect URL: " + endpoint); } } ``` -------------------------------- ### Python Example Source: https://docs.browserless.io/browserql/writing-bql/exporting-scripts Example of how to use the BrowserQL API with Python to extract job titles and links. ```APIDOC ```python import http.client from bs4 import BeautifulSoup import json conn = http.client.HTTPSConnection("production-sfo.browserless.io") payload = '{"query":"mutation ExtractJobsHTML {\n goto(url: \"https://news.ycombinator.com\", waitUntil: firstMeaningfulPaint) {\n status\n }\n \n click(selector: \"span.pagetop > a[href=\'jobs\']\") {\n x\n y\n }\n \n html {\n html\n }\n}","variables":null,"operationName":"ExtractJobsHTML"}' headers = {"Content-Type": "application/json"} conn.request( "POST", "/chromium/bql?token=YOUR_API_TOKEN_HERE", payload, headers, ) res = conn.getresponse() response = res.read() response_json = json.loads(response.decode("utf-8")) html = response_json["data"]["html"]["html"] soup = BeautifulSoup(html, "html.parser") titles_and_links = [] for job in soup.find_all("tr", class_="athing"): title_tag = job.find("a") if title_tag: titles_and_links.append( {"title": title_tag.text.strip(), "link": title_tag["href"].strip()} ) print(titles_and_links) ``` ``` -------------------------------- ### JavaScript Example Source: https://docs.browserless.io/browserql/writing-bql/exporting-scripts Example of how to use the BrowserQL API with JavaScript to extract job titles and links. ```APIDOC ```javascript const { JSDOM } = require("jsdom"); async function ExtractJobsHTML() { const url = "https://production-sfo.browserless.io/chromium/bql?token=YOUR_API_TOKEN_HERE"; const options = { method: 'POST', body: '{"query":"mutation ExtractJobsHTML {\n goto(url: \"https://news.ycombinator.com\", waitUntil: firstMeaningfulPaint) {\n status\n }\n \n click(selector: \"span.pagetop > a[href=\'jobs\']\") {\n x\n y\n }\n \n html {\n html\n }\n}","variables":null,"operationName":"ExtractJobsHTML"}' }; let response; try { response = await fetch(url, options); } catch (error) { console.error(error); } const json = await response.json(); const html = json.data.html.html; const dom = new JSDOM(html); const document = dom.window.document; const rows = document.querySelectorAll("tr.athing"); const titlesAndLinks = []; rows.forEach((row) => { const anchor = row.querySelector("a"); if (anchor) { titlesAndLinks.push({ title: anchor.textContent.trim(), link: anchor.href.trim(), }); } }); console.log(titlesAndLinks); } ExtractJobsHTML(); ``` ``` -------------------------------- ### Browserless API Guides Source: https://docs.browserless.io/open-api Overview, BrowserQL, BaaS V2, REST APIs, Enterprise, and deprecated BaaS V1. ```APIDOC ## API Guides ### Overview Provides a general introduction to Browserless.io services. ### BrowserQL (Recommended) Details on using the BrowserQL query language for advanced data extraction. ### BaaS V2 Documentation for the second version of Browserless as a Service (BaaS). ### REST APIs Information on the available RESTful APIs for browser automation. ### Enterprise Guides for enterprise-level solutions and support. ### BaaS V1 (Deprecated) Information regarding the older version of BaaS, now deprecated. ``` -------------------------------- ### Docker Quick Start for Browserless Enterprise Source: https://docs.browserless.io/enterprise/quick-start This Docker command initiates a Browserless Enterprise container with specified concurrency and token. It maps port 3000 and uses the official Browserless Chromium image. Ensure you replace YOUR_TOKEN with your actual token. ```docker docker run \ --rm \ -p 3000:3000 \ -e "CONCURRENT=10" \ -e "TOKEN=YOUR_TOKEN" \ ghcr.io/browserless/chromium ``` -------------------------------- ### Docker Quickstart for Browserless Source: https://github.com/browserless/browserless This snippet shows the basic command to run the Browserless Chromium Docker image and how to access its documentation site. ```bash docker run -p 3000:3000 ghcr.io/browserless/chromium ``` ```bash Visit http://localhost:3000/docs to see the documentation site. ``` -------------------------------- ### Dockerfile Example: Install AWS SDK Source: https://docs.browserless.io/enterprise/docker/extending This Dockerfile extends the official Browserless Chromium image by adding the `aws-sdk` npm module. It demonstrates how to specify a base image and use `RUN` commands to install dependencies. ```dockerfile FROM ghcr.io/browserless/chromium:latest # Install the AWS SDK RUN npm install aws-sdk ``` -------------------------------- ### Puppeteer PDF Generation Guide (2025) Source: https://www.browserless.io/blog/ This guide provides copy-paste examples for generating PDFs from HTML using Puppeteer. It includes formatting tips, troubleshooting advice, and strategies for production-ready scaling, updated for 2025. ```javascript // Example for Puppeteer PDF generation const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.setContent('

Hello World

'); await page.pdf({ path: 'hn.pdf', format: 'A4' }); await browser.close(); })(); ``` -------------------------------- ### Launch Options (Query Parameters) Source: https://docs.browserless.io/browserql/launch-parameters Lists common launch options available as query parameters for configuring browser sessions. ```APIDOC ## Launch Options (Query Parameters) Available launch options that can be used directly in query strings: | Parameter | Description | Default | | -------------- | ------------------------------------------------------------------------------------------------------------------ | ------- | | `launch` | A JSON string containing Browserless-specific options and Chrome flags within the `args` array. | `{}` | | `token` | The authorization token required for API access. | `none` | | `timeout` | The maximum duration for a session in milliseconds. Sessions exceeding this duration will be automatically closed. | `60000` | | `headless` | Controls whether the browser runs in headless mode (no visible UI). | `true` | ``` -------------------------------- ### Conditional Recording Source: https://docs.browserless.io/baas/session-management/recording-liveurl An example demonstrating how to conditionally start recording based on the presence of a specific element. ```APIDOC ## Conditional Recording ### Description Implement logic to start recording only if a particular element exists within the browser page. This allows for more granular control over when session data is captured. ### Method Not Applicable (Node.js example using Puppeteer) ### Endpoint Not Applicable ### Parameters Not Applicable ### Request Body Not Applicable ### CDP Commands - **Browserless.startRecording**: Starts the recording process. ### Request Example ```javascript const hasLoginForm = await page.$('.login-form'); if (hasLoginForm) { await cdp.send('Browserless.startRecording'); } ``` ### Response Not Applicable ``` -------------------------------- ### Conditional Recording Based on Element Presence Source: https://docs.browserless.io/baas/session-management/recording-liveurl This example demonstrates how to conditionally start recording based on the presence of a specific element. It first checks if the '.login-form' element exists using `page.$` and only proceeds to start recording if the element is found. ```javascript const hasLoginForm = await page.$('.login-form'); if (hasLoginForm) { await cdp.send("Browserless.startRecording"); } ``` -------------------------------- ### Passing Launch Options Source: https://docs.browserless.io/browserql/launch-parameters Demonstrates the two primary methods for passing launch options to Browserless.io sessions: individual query parameters for simple settings and a 'launch' parameter with a JSON payload for complex configurations. ```APIDOC ## Passing Launch Options Browserless.io supports two primary methods for specifying launch options: 1. **Individual Query Parameters**: Append options directly to your session URL. This is suitable for simple boolean flags or single settings. * Example: `&headless=false` * Example: `&proxy=residential` 2. **Combined `launch` Parameter (JSON)**: For more complex configurations, use a single query parameter named `launch`. The value of this parameter should be a URL-encoded JSON string containing various Chrome flags and Browserless-specific settings. This is analogous to providing an options object to Puppeteer's `launch` function. * Example: `&launch=%7B%22headless%22%3Afalse%2C%22stealth%22%3Atrue%2C%22args%22%3A%5B%22--window-size=1920,1080%22%5D%7D` * This example configures a headful browser with stealth enabled and a specific window size. Browserless merges both methods if used concurrently, with individual parameters taking precedence over settings within the `launch` JSON object. It is recommended to use individual query parameters for simple toggles and the `launch` parameter for multiple, structured settings. ``` -------------------------------- ### Get Browserless Worker Metrics (C#) Source: https://docs.browserless.io/enterprise/utility-functions/metrics Fetches metrics for browserless workers using the /metrics endpoint. This C# example demonstrates how to make an HTTP GET request to the API, handle the response, and display the metrics. Ensure you replace 'YOUR_API_TOKEN_HERE' with your actual Browserless API token. The output is a JSON array of metric objects. ```csharp using System; using System.Net.Http; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { string TOKEN = "YOUR_API_TOKEN_HERE"; string url = $"https://production-sfo.browserless.io/metrics?token={TOKEN}"; using var client = new HttpClient(); try { var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); // Throws if HTTP status is 4xx or 5xx var result = await response.Content.ReadAsStringAsync(); Console.WriteLine("Response: " + result); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } } ``` -------------------------------- ### Initialize Amplitude Analytics Source: https://browserless.io/pricing Initializes Amplitude, a product analytics service, with a specified SDK version and configuration. Includes methods for event tracking and user identification. ```javascript !function(){"use strict";!function(e,t){var r=e.amplitude||{_q:[],_iq:{}};if(r.invoked)e.console&&console.error&&console.error("Amplitude snippet has been loaded.");else{var n=function(e,t){e.prototype[t]=function(){return this._q.push({name:t,args:Array.prototype.slice.call(arguments,0)}),this}},s=function(e,t,r){return function(n){e._q.push({name:t,args:Array.prototype.slice.call(r,0),resolve:n})}},o=function(e,t,r){e._q.push({name:t,args:Array.prototype.slice.call(r,0)})},i=function(e,t,r){e[t]=function(){if(r)return{promise:new Promise(s(e,t,Array.prototype.slice.call(arguments)))};o(e,t,Array.prototype.slice.call(arguments))}},a=function(e){for(var t=0;t { // This was puppeteer.launch() const browser = await puppeteer.connect({ browserWSEndpoint: "ws://localhost:3000?token=6R0W53R135510", }); const page = await browser.newPage(); await page.goto("http://www.example.com/"); const data = await page.screenshot(); browser.close(); return res.end(data, "binary"); }); app.listen(8080); ``` -------------------------------- ### Generate PDF with Proxy Sticky (Python) Source: https://docs.browserless.io/rest-apis/launch-parameters Provides a Python example for generating a PDF with sticky proxy enabled via the browserless.io API. It uses the `requests` library to make the POST request. ```python import requests TOKEN = "YOUR_API_TOKEN_HERE" url = f"https://production-sfo.browserless.io/pdf?token={TOKEN}&proxy=residential&proxySticky=true" headers = { "Cache-Control": "no-cache", "Content-Type": "application/json" } data = { "url": "https://example.com/", } response = requests.post(url, headers=headers, json=data) with open("output.pdf", "wb") as file: file.write(response.content) print("PDF saved as output.pdf") ``` -------------------------------- ### Connect to Browserless Enterprise with Puppeteer Source: https://docs.browserless.io/enterprise/quick-start This code snippet demonstrates how to connect to a Browserless Enterprise instance using the Puppeteer library. It requires the browser WebSocket endpoint and an authentication token. The output is a connected browser instance. ```javascript const browser = await puppeteer.connect({ browserWSEndpoint: "ws://localhost:3000?token=YOUR_TOKEN", }); ``` -------------------------------- ### Allow Specific CORS Methods with Docker Source: https://docs.browserless.io/enterprise/docker/config Configures which HTTP methods are allowed for CORS requests when CORS is enabled. By default, OPTIONS, POST, and GET are allowed. This example explicitly allows POST and DELETE methods. ```bash docker run \ -e "CORS=true" \ -e "CORS_ALLOW_METHODS=POST, DELETE" \ -p 3000:3000 \ ghcr.io/browserless/chromium ``` -------------------------------- ### Navigate to a Page using goto mutation Source: https://docs.browserless.io/browserql/writing-bql/language-basics This GraphQL mutation demonstrates how to navigate to a specified URL and wait until a particular condition (firstMeaningfulPaint) is met. It returns the status and time taken for the navigation. This is a fundamental step in most BQL scripts. ```graphql mutation ExampleName { goto( url: "https://example.com" waitUntil: firstMeaningfulPaint ) { status time }} ``` -------------------------------- ### Retrieve Session Statistics with /metrics API (Java) Source: https://docs.browserless.io/enterprise/utility-functions/metrics This Java example utilizes the `HttpClient` to make a GET request to the /metrics API. It includes the necessary API token and handles the response, printing the body to the console. ```java import java.io.*; import java.net.URI; import java.net.http.*; public class FetchMetrics { public static void main(String[] args) { String TOKEN = "YOUR_API_TOKEN_HERE"; String url = "https://production-sfo.browserless.io/metrics?token=" + TOKEN; HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(url)) .GET() .build(); try { HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("Response: " + response.body()); } catch (Exception e) { e.printStackTrace(); } } } ``` -------------------------------- ### Generate PDF with Residential Proxy (Javascript) Source: https://docs.browserless.io/rest-apis/launch-parameters Provides a Javascript example using the fetch API to generate a PDF with a residential proxy. It includes setting up the token, URL, headers, and data, then saving the PDF to a file. ```javascript import fs from 'fs/promises'; const TOKEN = "YOUR_API_TOKEN_HERE"; const url = `https://production-sfo.browserless.io/pdf?token=${TOKEN}&proxy=residential`; const headers = { "Cache-Control": "no-cache", "Content-Type": "application/json" }; const data = { url: "https://example.com/", }; const generatePDF = async () => { const response = await fetch(url, { method: 'POST', headers: headers, body: JSON.stringify(data) }); const pdfBuffer = await response.arrayBuffer(); await fs.writeFile("output.pdf", Buffer.from(pdfBuffer)); console.log("PDF saved as output.pdf"); }; generatePDF(); ``` -------------------------------- ### Retrieve Session Statistics with /metrics API (cURL) Source: https://docs.browserless.io/enterprise/utility-functions/metrics This example demonstrates how to fetch session statistics using a GET request to the /metrics endpoint. It requires a valid API token and returns an array of session data. ```shell curl -X GET \ https://production-sfo.browserless.io/metrics?token=YOUR_API_TOKEN_HERE ``` -------------------------------- ### cURL: Screenshot with Proxy Support Source: https://docs.browserless.io/baas/libraries/php This example shows how to use cURL to make a POST request to the Browserless API for capturing a screenshot with proxy support enabled. It sends a JSON payload with URL and options. ```curl "https://production-sfo.browserless.io/screenshot?token=YOUR_API_TOKEN_HERE&proxy=residential", CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 60, CURLOPT_CUSTOMREQUEST => "POST", CURLOPT_POSTFIELDS => json_encode([ "url" => "https://example.com/", "options" => [ "fullPage" => true ] ]), CURLOPT_HTTPHEADER => [ "Content-Type: application/json" ], ]); $response = curl_exec($curl); curl_close($curl); ``` -------------------------------- ### Capture Screenshot with Playwright (C#) Source: https://docs.browserless.io/enterprise/docker/quickstart This C# ASP.NET Core application uses Playwright to connect to Browserless via CDP, capture a PNG screenshot of a given URL after a 5-second delay, and return it. It requires the Microsoft.Playwright NuGet package. ```csharp using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Microsoft.Playwright; var builder = WebApplication.CreateBuilder(args); var app = builder.Build(); app.MapGet("/image", async context =>{ try { var playwright = await Playwright.CreateAsync(); var browser = await playwright.Chromium.ConnectOverCDPAsync("ws://localhost:3000?token=6R0W53R135510"); var page = await (await browser.NewContextAsync()).NewPageAsync(); await page.GotoAsync("http://www.example.com/"); await Task.Delay(5000); var screenshot = await page.ScreenshotAsync(new PageScreenshotOptions { Type = ScreenshotType.Png }); context.Response.ContentType = "image/png"; await context.Response.Body.WriteAsync(screenshot); await browser.CloseAsync(); } catch (Exception e) { context.Response.StatusCode = 500; await context.Response.WriteAsync("Error capturing screenshot: " + e.Message); } }); app.Run("http://localhost:8080"); ``` -------------------------------- ### BrowserQL Connection URL and Authentication Source: https://docs.browserless.io/browserql/connection-urls This section explains how to get your API token from the Browserless dashboard and add it to your connection URL for authentication. It highlights the importance of securing your token and provides an example of a valid connection URL. ```APIDOC ## Get Your API Token 1. Go to the [Browserless dashboard](https://account.browserless.io/) 2. Sign up or log in to your account. 3. Copy your API token from the dashboard. ## Add Token to URL Append your API token to the URL query string as `?token=YOUR_TOKEN`. This is mandatory for authentication; invalid tokens will result in HTTP 401/403 errors. **Example:** `https://production-sfo.browserless.io/chromium/bql?token=094632bb-e326-4c63-b953-82b55700b14c` **Security Note:** Keep this URL secure and never expose it in client-side code or logs. ``` -------------------------------- ### Capture Screenshot with Playwright (Java) Source: https://docs.browserless.io/enterprise/docker/quickstart This Java Spark application demonstrates connecting to Browserless using Playwright's Java API, navigating to a URL, waiting, capturing a screenshot, and sending it as a PNG response. It requires Playwright for Java and Spark Java. ```java import com.microsoft.playwright.*; import static spark.Spark.*; import java.io.OutputStream; public class PlaywrightImageServer { public static void main(String[] args) { port(8080); get("/image", (req, res) -> { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium().connectOverCDP("ws://localhost:3000?token=6R0W53R135510"); BrowserContext context = browser.newContext(); Page page = context.newPage(); page.navigate("http://www.example.com/"); page.waitForTimeout(5000); byte[] screenshot = page.screenshot(new Page.ScreenshotOptions().setType("png")); browser.close(); res.type("image/png"); OutputStream outputStream = res.raw().getOutputStream(); outputStream.write(screenshot); outputStream.flush(); return res.raw(); } catch (Exception e) { res.status(500); return "Error capturing screenshot: " + e.getMessage(); } }); } } ``` -------------------------------- ### Get Webpage Title with Pyppeteer (Python) Source: https://docs.browserless.io/baas/connect-puppeteer Connects to Browserless.io using a WebSocket endpoint and fetches the title of a webpage. This example requires the pyppeteer library and a Browserless API token. It showcases navigation and title retrieval in Python. ```python import asyncio from pyppeteer import connect TOKEN = "YOUR_API_TOKEN_HERE" async def get_page_title(): # Connect to Browserless using WebSocket endpoint browser = await connect({ "browserWSEndpoint": f"wss://production-sfo.browserless.io/?token={TOKEN}" }) page = await browser.newPage() await page.goto("https://www.example.com/") title = await page.title() print(f"The page's title is: {title}") await browser.close() if __name__ == "__main__": asyncio.run(get_page_title()) ``` -------------------------------- ### Install Packages for Browserless AI Integration Source: https://docs.browserless.io/ai-integrations/vercel-ai-sdk Installs necessary packages including the Vercel AI SDK, Browserless AI, Puppeteer Core, OpenAI client, Zod for validation, and Prettier for code formatting. ```bash npm install @vercel/ai @browserless/ai puppeteer-core openai zod prettier ```