{ "success": true, "sessionId": "a1b2c3d4e5f6", "taskId": "x9y8z7w6v5u4", "status": "pending", "pollUrl": "https://api.webrun.ai/task/a1b2c3d4e5f6/x9y8z7w6v5u4", "message": "Task still running. Poll GET /task/:sessionId/:taskId for result."}
Most browser tasks complete in 10-40 seconds. The API waits up to 50 seconds before responding, so typical requests return results immediately: no polling required.
Pattern 2: Multi-Task Session
For workflows that require multiple sequential tasks in the same browser session.Step 1: Create persistent session
Cost Tip: Set terminateOnCompletion: true on your last task to auto-close the session and avoid idle charges. Sessions remain billable until terminated or timed out.
Pattern 3: Polling for Results
When a task returns status: "pending", poll until completion:
async function runTask(prompt, apiKey) { const response = await fetch("https://api.webrun.ai/start/run-task", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiKey}` }, body: JSON.stringify({ task: { prompt } }) }); const data = await response.json(); // Inline result - return immediately if (data.status === "complete") { return data.result; } // Pending - poll for result if (data.status === "pending") { return await pollForResult(data.sessionId, data.taskId, apiKey); } throw new Error(data.message || "Task failed");}async function pollForResult(sessionId, taskId, apiKey) { const maxAttempts = 60; // 2 minutes max const interval = 2000; // Poll every 2 seconds for (let i = 0; i < maxAttempts; i++) { const res = await fetch( `https://api.webrun.ai/task/${sessionId}/${taskId}`, { headers: { "Authorization": `Bearer ${apiKey}` } } ); const data = await res.json(); if (data.type === "task_completed") return data; if (data.type === "guardrail_trigger") return data; if (!data.success && data.status === "failed") throw new Error(data.error); // Still running - wait and retry await new Promise(r => setTimeout(r, interval)); } throw new Error("Task timeout after 2 minutes");}// Usageconst result = await runTask("Search Google for Anthropic", "wr_xxx");console.log(result.data.message);console.log(`Cost: $${result.usage.cost}`);
Complete Examples
Example 1: Simple Task Execution
const API_KEY = "wr_xxxxxxxxxxxx";async function searchGoogle(query) { const response = await fetch("https://api.webrun.ai/start/run-task", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ task: { prompt: `Search Google for "${query}" and summarize the first result` } }) }); const data = await response.json(); if (data.status === "complete") { return data.result.data.message; } else if (data.status === "pending") { // Poll for result const result = await pollForResult(data.sessionId, data.taskId, API_KEY); return result.data.message; } throw new Error(data.message || "Task failed");}// Usageconst summary = await searchGoogle("Anthropic Claude");console.log(summary);
Example 2: Multi-Step Workflow
const API_KEY = "wr_xxxxxxxxxxxx";const BASE = "https://api.webrun.ai";async function amazonProductResearch(productName) { // 1. Create session const session = await fetch(`${BASE}/start/start-session`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ mode: "default", task: { prompt: "Go to amazon.com", startingUrl: "https://amazon.com" } }) }).then(r => r.json()); const sessionId = session.sessionId; // 2. Search for product const searchTask = await fetch(`${BASE}/start/send-message`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ sessionId, message: { actionType: "newTask", newState: "start", prompt: `Search for "${productName}" and list the top 3 results with prices` } }) }).then(r => r.json()); // Poll if needed let searchResult; if (searchTask.pending) { searchResult = await pollForResult(sessionId, searchTask.taskId, API_KEY); } else { searchResult = searchTask.result; } console.log("Search results:", searchResult.data.message); // 3. Add first item to cart const cartTask = await fetch(`${BASE}/start/send-message`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ sessionId, message: { actionType: "newTask", newState: "start", prompt: "Add the first product to cart", terminateOnCompletion: true // Auto-close session } }) }).then(r => r.json()); // Poll if needed let cartResult; if (cartTask.pending) { cartResult = await pollForResult(sessionId, cartTask.taskId, API_KEY); } else { cartResult = cartTask.result; } return { searchResults: searchResult.data.message, cartStatus: cartResult.data.message };}// Usageconst results = await amazonProductResearch("wireless keyboard");console.log(results);
Example 3: Using a Proxy
Route traffic through a proxy for geographic targeting or IP management. The proxy field is top-level, alongside environmentId:
See the Proxies guide for custom proxy configuration and best practices.
Example 4: Using an Environment
Attach an environment to reuse saved cookies and login sessions across tasks:
const API_KEY = "wr_xxxxxxxxxxxx";async function runWithEnvironment(environmentId, prompt) { const response = await fetch("https://api.webrun.ai/start/run-task", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ environmentId, task: { prompt } }) }); return response.json();}// First run: log in and save cookies to the environment's profileawait runWithEnvironment("<ENV_ID>", "Go to amazon.com and log in");// Subsequent runs: environment has saved cookies, no login neededconst result = await runWithEnvironment( "<ENV_ID>", "Go to amazon.com and check my recent orders");console.log(result);
Example 5: Authenticated Task with Secrets
Use secrets to provide credentials upfront so the agent can authenticate without guardrail interruptions:
async function loginAndExtractWithSecrets(url) { const BASE = "https://api.webrun.ai"; const API_KEY = "wr_xxxxxxxxxxxx"; const session = await fetch(`${BASE}/start/start-session`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ mode: "default", task: { prompt: `Go to ${url}, log in, and extract all user data from the dashboard`, startingUrl: url, terminateOnCompletion: true, secrets: [ { match: `*.${new URL(url).hostname}`, fields: { email: process.env.SITE_EMAIL, password: process.env.SITE_PASSWORD } } ] } }) }).then(r => r.json()); // Poll for result, no guardrail handling needed const taskId = session.taskId || session.sessionId; return await pollForResult(session.sessionId, taskId, API_KEY);}
Example 6: Handling Guardrails
async function loginAndExtractData(url, credentials) { const BASE = "https://api.webrun.ai"; const API_KEY = "wr_xxxxxxxxxxxx"; // Create session with login task const session = await fetch(`${BASE}/start/start-session`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ mode: "default", task: { prompt: `Go to ${url} and log in`, startingUrl: url } }) }).then(r => r.json()); const sessionId = session.sessionId; // Start login task const loginTask = await fetch(`${BASE}/start/send-message`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ sessionId, message: { actionType: "newTask", newState: "start", prompt: "Log in to the website" } }) }).then(r => r.json()); // Poll for result const taskId = loginTask.taskId; let result = await pollForResult(sessionId, taskId, API_KEY); // Handle guardrail if triggered if (result.type === "guardrail_trigger") { console.log("Guardrail:", result.data.value); // Provide credentials await fetch(`${BASE}/start/send-message`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ sessionId, message: { actionType: "guardrail", prompt: `Username: ${credentials.username}, Password: ${credentials.password}`, newState: "resume" } }) }); // Continue polling result = await pollForResult(sessionId, taskId, API_KEY); } // Extract data after login const extractTask = await fetch(`${BASE}/start/send-message`, { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ sessionId, message: { actionType: "newTask", newState: "start", prompt: "Extract all user data from the dashboard", terminateOnCompletion: true } }) }).then(r => r.json()); if (extractTask.pending) { return await pollForResult(sessionId, extractTask.taskId, API_KEY); } return extractTask.result;}