Skip to main content

/function API

Execute custom Puppeteer code via HTTP requests without installing libraries. The /function endpoint accepts custom JavaScript code with a page object (Puppeteer page) and optional context data from your JSON body.

Functions should return an object with two properties: data (Buffer, JSON, or plain text) and type (Content-Type string). Browserless reads both of these from your functions' return value and resolves the request appropriately.

You can view the complete Function API OpenAPI specification.

Quick Start

JS Code

export default async function ({ page }) {
const rndNumber = () => {
return Math.floor(Math.random() * (10**6 - 0));
};

await page.goto("https://example.com/");
const url = await page.title();
const numbers = [...Array(5)].map(() => rndNumber());

return {
data: {
url,
numbers,
},
// Make sure to match the appropriate content here
type: "application/json",
};
}
curl -X POST \
"https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" \
-H 'Content-Type: application/javascript' \
-d 'export default async function ({ page }) {
const rndNumber = () => {
return Math.floor(Math.random() * (10**6 - 0));
};

await page.goto("https://example.com/");
const url = await page.title();
const numbers = [...Array(5)].map(() => rndNumber());

return {
data: {
url,
numbers,
},
// Make sure to match the appropriate content here
type: "application/json",
};
}'

Response

{
"data": {
"url": "Example Domain",
"numbers": [
854246,
114512,
212580,
482122,
107878
]
},
"type": "application/json"
}

Advanced Usage

The /function API can return other file types beyond JSON, such as PDF files. In this example, we'll generate a full-page PDF of a website by calculating the page height and formatting the PDF accordingly.

JS Code

export default async function ({ page }) {
await page.goto("https://es.wikipedia.org/wiki/Web_scraping", { waitUntil: 'networkidle2', timeout: 60000 });
await page.emulateMediaType('screen');
const height = await page.evaluate(() => {
return document.documentElement.scrollHeight - document.documentElement.clientHeight;
});
const pdf = await page.pdf({
printBackground: true,
pageRanges: '1',
height: `${height}px`,
width: '1800px'
});
return pdf;
}
curl -X POST \
'https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE' \
--header 'Content-Type: application/javascript' \
--data 'export default async function ({ page }) {
await page.goto("https://es.wikipedia.org/wiki/Web_scraping", { waitUntil: '\''networkidle2'\'', timeout: 60000 });
await page.emulateMediaType('\''screen'\'');
const height = await page.evaluate(() => {
return document.documentElement.scrollHeight - document.documentElement.clientHeight;
});
const pdf = await page.pdf({
printBackground: true,
pageRanges: '\''1'\'',
height: `${height}px`,
width: '\''1800px'\''
});
return pdf;
}'

Debug your code

Before sending your code through the /function API, you can test and troubleshoot it using our Live Debugger feature. This powerful tool allows you to write and execute your Puppeteer code in a browser environment, making it easy to iterate and debug before making API calls.

You can access the Live Debugger directly from your account page. Once your code is working as expected, simply copy and paste it as the request body and send it with the application/javascript content-type header to the /function endpoint.

For more details on how to use the Live Debugger and its features, see our Live Debugger documentation.

Importing libraries

Since the /function API uses ESM modules, you can use import syntax over HTTP to load moules. For instance, let's try loading the Fake module.

JS Code

import { faker } from "https://esm.sh/@faker-js/faker";

export default async function () {
const Internet = faker.internet;
const rndData = [...Array(5)].map(() => ({
domain: Internet.domainName(),
ip: Internet.ip(),
mac: Internet.mac(),
protocol: Internet.protocol(),
}));

return {
data: { domains: rndData },
type: "application/json",
};
}
curl -X POST \
"https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" \
-H 'Content-Type: application/javascript' \
-d 'import { faker } from "https://esm.sh/@faker-js/faker";

export default async function () {
const Internet = faker.internet;
const rndData = [...Array(5)].map(() => ({
domain: Internet.domainName(),
ip: Internet.ip(),
mac: Internet.mac(),
protocol: Internet.protocol(),
}));

return {
data: { domains: rndData },
type: "application/json",
};
}'

JSON API

You can also use the /function API for sending a JSON payload. For that you must send an object with the following values:

  • code: String, required — custom function code.
  • context: Object, optional — value used to pass context values and arguments to the code

Example

JS Code

import { faker } from "https://esm.sh/@faker-js/faker";

export default async function ({ context }) {
const Internet = faker.internet;
const rndData = [...Array(context.len)].map(() => ({
domain: Internet.domainName(),
ip: Internet.ip(),
mac: Internet.mac(),
protocol: Internet.protocol(),
}));

return {
data: {
domains: rndData,
length: context.len
},
type: "application/json",
};
}
curl --request POST \
--url 'https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE' \
--header 'Content-Type: application/json' \
# Minified code
--data '{
"code": "import{faker as a}from\"https://esm.sh/@faker-js/faker\";export default async function({context:o}){let t=a.internet,e=[...Array(o.len)].map(()=>({domain:t.domainName(),ip:t.ip(),mac:t.mac(),protocol:t.protocol()}));return{data:{domains:e,length:o.len},type:`application/json`}};",
"context": {
"len": 10
}
}'

Exception handling

When working with the /function API, you can catch exceptions and handle errors gracefully. This is particularly useful for debugging and providing meaningful error responses when automation fails.

The following example shows how to implement comprehensive error, allowing you to:

  • Capture detailed error information including the error message, stack trace, and error type
  • Take a screenshot when an error occurs for visual debugging
  • Handle screenshot capture errors gracefully
  • Return both successful data and error information in a structured format

JS Code

export default async ({ page }) => {
let error;
let title;

try {
await page.goto('https://www.example.com');
title = await page.title();
await page.click('.nonexistent-button'); // This will throw
} catch (err) {
const errorDetails = {
message: err.message,
stack: err.stack,
name: err.name,
};

try {
const screenshot = await page.screenshot({ encoding: 'base64' });
errorDetails.screenshot = screenshot;
} catch (screenshotErr) {
errorDetails.screenshotError = {
message: screenshotErr.message,
stack: screenshotErr.stack,
name: screenshotErr.name,
};
}
error = errorDetails;
}
return {
data: {
title,
error,
},
};
};
curl -X POST \
"https://production-sfo.browserless.io/function?token=YOUR_API_TOKEN_HERE" \
-H 'Content-Type: application/javascript' \
-d 'export default async ({ page }) => {
let error;
let title;

try {
await page.goto("https://www.example.com");
title = await page.title();
await page.click(".nonexistent-button"); // This will throw
} catch (err) {
const errorDetails = {
message: err.message,
stack: err.stack,
name: err.name,
};

try {
const screenshot = await page.screenshot({ encoding: "base64" });
errorDetails.screenshot = screenshot;
} catch (screenshotErr) {
errorDetails.screenshotError = {
message: screenshotErr.message,
stack: screenshotErr.stack,
name: screenshotErr.name,
};
}
error = errorDetails;
}
return {
data: {
title,
error,
},
};
};'

Response

{
"data": {
"title": "Example Domain",
"error": {
"message": "No node found for selector: .nonexistent-button",
"stack": "Error: No node found for selector: .nonexistent-button\n at ...",
"name": "Error",
"screenshot": "iVBORw0KGgoAAAANSUhEUgAAA..."
}
}
}
Session Persistence

The /function API, like all REST APIs, automatically closes the browser session after execution completes. If you need to persist sessions or keep browsers alive between requests, consider using BaaS with session management or BrowserQL with the reconnect mutation.