Skip to main content
The execute-code tool runs a TypeScript snippet inside an existing browser session, letting you perform custom browser logic without managing your own automation infrastructure.
Code Execution is available from the Growth tier and above.
Create a session with POST /v1/sessions, then call POST /v1/tools/execute-code with sessionId in the query string. The request body code field is an async function body with injected page, browser, context, sessionId, and anchorClient. On success, the API returns output as a JSON string of your return value. See the full API reference for details.

Code example

const apiKey = process.env.ANCHOR_API_KEY;

async function createSession() {
  const res = await fetch('https://api.anchorbrowser.io/v1/sessions', {
    method: 'POST',
    headers: {
      'anchor-api-key': apiKey,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({}),
  });
  const json = await res.json();
  if (!res.ok) {
    throw new Error(`create session failed: ${res.status} ${JSON.stringify(json)}`);
  }
  return json.data.id;
}

const sessionId = await createSession();
console.log('session', sessionId);

const res = await fetch(`https://api.anchorbrowser.io/v1/tools/execute-code?sessionId=${sessionId}`, {
  method: 'POST',
  headers: {
    'anchor-api-key': apiKey,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    code: "await page.goto('https://news.ycombinator.com'); const title = await page.title(); return { title };",
  }),
});
const body = await res.json();
console.log(body);