Open source

connectOverCDP(wsEndpoint)

Attaches k6 to an existing Chromium-based browser over the Chrome DevTools Protocol (CDP), and returns a Browser you can use exactly like a k6-managed one.

Because you connect from inside the iteration, you can compute the WebSocket endpoint at runtime. For instance, you can request a browser session from your provider’s API in setup() and pass the endpoint to your iterations.

Note

connectOverCDP doesn’t need the browser scenario option. k6 doesn’t launch a browser, so there’s no browser type for it to resolve. The browser module options that apply to an existing browser, such as K6_BROWSER_TIMEOUT and K6_BROWSER_DEBUG, are still honored.

ParameterTypeDefaultDescription
wsEndpointstring-Required. The WebSocket endpoint of the browser’s CDP interface, for example ws://localhost:9222/devtools/browser/<BROWSER_ID>. Must use the ws or wss scheme.

Returns

TypeDescription
Promise<Browser>A Promise that fulfills with a Browser object. Unlike the k6-managed browser, it also exposes close().

Connection lifecycle

k6 manages the connection for you and closes it at the end of the iteration, the same way it does for a browser it launched itself. Call browser.close() when you want to release it earlier.

Closing the connection doesn’t stop the browser itself. You own its lifecycle, so it keeps running.

Examples

Connect to a local browser

Start Chrome with the --remote-debugging-port flag, then read its WebSocket endpoint from http://localhost:9222/json/version (the webSocketDebuggerUrl field) and pass it to k6 as an environment variable:

JavaScript
import { chromium } from 'k6/browser';

export default async function () {
  const browser = await chromium.connectOverCDP(__ENV.CDP_WS_URL);
  const page = await browser.newPage();

  try {
    await page.goto('https://quickpizza.grafana.com/');
    console.log(`title: ${await page.title()}`);
  } finally {
    await page.close();
    await browser.close();
  }
}

Then, run the test with this command:

Bash
CDP_WS_URL=ws://localhost:9222/devtools/browser/<BROWSER_ID> k6 run script.js

Connect to a browser provider

When a third-party provider creates the browser session, request the endpoint once in setup() and share it with every iteration:

JavaScript
import http from 'k6/http';
import { chromium } from 'k6/browser';

export function setup() {
  const res = http.post('https://provider.example/v1/sessions');
  return { wsURL: res.json().connectUrl };
}

export default async function (data) {
  const browser = await chromium.connectOverCDP(data.wsURL);
  const page = await browser.newPage();

  try {
    await page.goto('https://quickpizza.grafana.com/');
  } finally {
    await page.close();
    await browser.close();
  }
}