Menu

Important: This documentation is about an older version. It's relevant only to the release noted, many of the features and functions have been updated or replaced. Please view the current version.

Open source RSS

browser

Caution

This is an experimental module.

While we intend to keep experimental modules as stable as possible, we may need to introduce breaking changes. This could happen at future k6 releases until the module becomes fully stable and graduates as a k6 core module. For more information, refer to the extension graduation process.

Experimental modules maintain a high level of stability and follow regular maintenance and security measures. Feel free to open an issue if you have any feedback or suggestions.

The browser module APIs aim for rough compatibility with the Playwright API for NodeJS.

Note that because k6 does not run in NodeJS, the browser module APIs will slightly differ from their Playwright counterparts.

You can find examples of using the browser module API in our getting started guide.

Note

To work with the browser module, make sure you are using the latest k6 version.

Properties

The table below lists the properties you can import from the browser module ('k6/experimental/browser').

PropertyDescription
browserThe browser module API is the entry point for all your tests. See the example and the API below.
devicesReturns predefined emulation settings for many end-user devices that can be used to simulate browser behavior on a mobile device. See the devices example below.

Browser Module API

The browser module is the entry point for all your tests, and it is what interacts with the actual web browser via Chrome DevTools Protocol (CDP). It manages:

  • BrowserContext which is where you can set a variety of attributes to control the behavior of pages;
  • and Page which is where your rendered site is displayed.
MethodDescription
browser.context()Returns the current BrowserContext.
browser.closeContext()Closes the current BrowserContext.
browser.isConnected Indicates whether the CDP connection to the browser process is active or not.
browser.newContext([options]) Creates and returns a new BrowserContext.
browser.newPage([options]) Creates a new Page in a new BrowserContext and returns the page. Pages that have been opened ought to be closed using Page.close. Pages left open could potentially distort the results of Web Vital metrics.
browser.version()Returns the browser application’s version.

Example

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

export const options = {
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
  thresholds: {
    checks: ['rate==1.0'],
  },
};

export default async function () {
  const page = browser.newPage();

  try {
    await page.goto('https://test.k6.io/');
  } finally {
    page.close();
  }
}

Then, you can run the test with this command. Also, see the browser module options for customizing the browser module’s behavior using environment variables.

bash
$ k6 run script.js
docker
# WARNING!
# The grafana/k6:master-with-browser image launches a Chrome browser by setting the
# 'no-sandbox' argument. Only use it with trustworthy websites.
#
# As an alternative, you can use a Docker SECCOMP profile instead, and overwrite the
# Chrome arguments to not use 'no-sandbox' such as:
# docker container run --rm -i -e K6_BROWSER_ARGS='' --security-opt seccomp=$(pwd)/chrome.json grafana/k6:master-with-browser run - <script.js
#
# You can find an example of a hardened SECCOMP profile in:
# https://raw.githubusercontent.com/jfrazelle/dotfiles/master/etc/docker/seccomp/chrome.json.
docker run --rm -i grafana/k6:master-with-browser run - <script.js
windows
C:\k6> k6 run script.js
windows-powershell
PS C:\k6> k6 run script.js

Browser-level APIs

k6 ClassDescription
BrowserContext Enables independent browser sessions with separate Pages, cache, and cookies.
ElementHandle Represents an in-page DOM element.
Frame Access and interact with the Page.’s Frames.
JSHandleRepresents an in-page JavaScript object.
KeyboardUsed to simulate the keyboard interactions with the associated Page.
LocatorThe Locator API makes it easier to work with dynamically changing elements.
MouseUsed to simulate the mouse interactions with the associated Page.
Page Provides methods to interact with a single tab in a browser.
Request Used to keep track of the request the Page makes.
Response Represents the response received by the Page.
TouchscreenUsed to simulate touch interactions with the associated Page.
WorkerRepresents a WebWorker.

Browser Module Options

You can customize the behavior of the browser module by providing browser options as environment variables.

Environment VariableDescription
K6_BROWSER_ARGSExtra command line arguments to include when launching browser process. See this link for a list of Chromium arguments. Note that arguments should not start with -- (see the example).
K6_BROWSER_DEBUGAll CDP messages and internal fine grained logs will be logged if set to true.
K6_BROWSER_EXECUTABLE_PATHOverride search for browser executable in favor of specified absolute path.
K6_BROWSER_HEADLESSShow browser GUI or not. true by default.
K6_BROWSER_IGNORE_DEFAULT_ARGSIgnore any of the default arguments included when launching a browser process.
K6_BROWSER_TIMEOUTDefault timeout to use for various actions and navigation. '30s' if not set.

The following command passes the browser module options as environment variables to launch a headful browser with custom arguments.

bash
$ K6_BROWSER_HEADLESS=false K6_BROWSER_ARGS='show-property-changed-rects' k6 run script.js
docker
# WARNING!
# The grafana/k6:master-with-browser image launches a Chrome browser by setting the
# 'no-sandbox' argument. Only use it with trustworthy websites.
#
# As an alternative, you can use a Docker SECCOMP profile instead, and overwrite the
# Chrome arguments to not use 'no-sandbox' such as:
# docker container run --rm -i -e K6_BROWSER_ARGS='' --security-opt seccomp=$(pwd)/chrome.json grafana/k6:master-with-browser run - <script.js
#
# You can find an example of a hardened SECCOMP profile in:
# https://raw.githubusercontent.com/jfrazelle/dotfiles/master/etc/docker/seccomp/chrome.json.
docker run --rm -i -e K6_BROWSER_HEADLESS=false -e K6_BROWSER_ARGS='show-property-changed-rects' grafana/k6:master-with-browser run - <script.js
windows
C:\k6> set "K6_BROWSER_HEADLESS=false" && set "K6_BROWSER_ARGS='show-property-changed-rects' " && k6 run script.js
windows-powershell
PS C:\k6> $env:K6_BROWSER_HEADLESS="false" ; $env:K6_BROWSER_ARGS='show-property-changed-rects' ; k6 run script.js

Default arguments

List of default arguments included when launching the browser process. You can pass one or more of the arguments to the K6_BROWSER_IGNORE_DEFAULT_ARGS environment variable when starting a test for the ones you want to ignore.

Note

The starting ‘–’ have been omitted from the argument names in these lists.
ArgumentValueDescription
disable-background-networkingtrueDisables several subsystems which run network requests in the background. This is used during network performance testing to avoid measurement noise.
enable-featuresNetworkService,
NetworkServiceInProcess
Comma-separated list of feature names to enable.
disable-background-timer-throttlingtrueDisables task throttling of timer tasks from background pages.
disable-backgrounding-occluded-windowstrueDisables backgrounding renders for occluded windows. Done for tests to avoid nondeterministic behavior.
disable-breakpadtrueDisables the crash reporting.
disable-component-extensions
-with-background-pages
trueDisables default component extensions with background pages. Useful for performance tests where these pages may interfere with results.
disable-default-appstrueDisables the installation of default apps on the first run. This is used during automated testing.
disable-dev-shm-usagetrueThe /dev/shm partition is too small in certain VM environments, causing Chrome to fail or crash. This flag provides a work-around for this issue (a temporary directory will always be used to create anonymous shared memory files).
disable-extensionstrueDisables extensions.
disable-featuresImprovedCookieControls,
LazyFrameLoading,
GlobalMediaControls,
DestroyProfileOnBrowserClose,
MediaRouter,
AcceptCHFrame
Comma-separated list of feature names to disable.
disable-hang-monitortrueSuppresses hang monitor dialogs in renderer processes. This may allow slow unload handlers on a page to prevent the tab from closing, but the Task Manager can be used to terminate the offending process in this case.
disable-ipc-flooding-protectiontrueDisables the IPC flooding protection. It is activated by default. Some javascript functions can be used to flood the browser process with IPC. This protection limits the rate at which they can be used.
disable-popup-blockingtrueDisables pop-up blocking.
disable-prompt-on-reposttrueUsually, when the user attempts to navigate to a page that was the result of a post request, the browser prompts to make sure that’s the intention of the user. This switch may be used to disable that check during automated testing.
disable-renderer-backgroundingtruePrevents renderer process backgrounding when set.
force-color-profilesrgbForces all monitors to be treated as though they have the specified color profile. Accepted values are “srgb” and “generic-rgb” (currently used by Mac layout tests) and “color-spin-gamma24” (used by layout tests).
metrics-recording-onlytrueEnables the recording of metrics reports but disables reporting. This executes all the code that a normal client would use for reporting, except the report is dropped rather than sent to the server. This is useful for finding issues in the metrics code during UI and performance tests.
no-first-runtrueSkips the “First Run” tasks, whether or not it’s the first run, and the “What’s New” page. This does not drop the “First Run” sentinel and thus doesn’t prevent “First Run” from occurring the next time Chromium is launched without this flag. It also does not update the last “What’s New” milestone, so it does not prevent “What’s New” from occurring the next time Chromium is launched without this flag.
enable-automationtrueEnables indication that the browser is controlled by automation.
password-storebasicSpecifies which encryption storage backend to use. The possible values are kwallet, kwallet5, gnome, gnome-keyring, gnome-libsecret, and basic. Any other value will lead to Chromium detecting the best backend automatically.
use-mock-keychaintrueUses mock keychain on Mac to prevent the blocking permissions dialog about: “Chrome wants to use your confidential information stored in your keychain.”
no-service-autoruntrueDisables the service process from adding itself as an autorun process. This does not delete existing autorun registrations, it just prevents the service from registering a new one.
no-startup-windowtrueDoes not automatically open a browser window on startup (used when launching Chrome for the purpose of hosting background apps).
no-default-browser-checktrueDisables the default browser check. Useful for UI/browser tests where we want to avoid having the default browser info-bar displayed.
headlesstrue/falseRun in headless mode, i.e., without a UI or display server dependencies. Set by K6_BROWSER_HEADLESS environment variable (default true).
window-size800,600Sets the initial window size. Provided as string in the format “800,600”.

Additionally if headless mode is set to true in browser options, the following arguments are also set:

ArgumentValueDescription
hide-scrollbarstruePrevents creating scrollbars for web content. Useful for taking consistent screenshots.
mute-audiotrueMutes audio sent to the audio device so it is not audible during automated testing.
blink-settingsprimaryHoverType=2,availableHoverTypes=2,
primaryPointerType=4,availablePointerTypes=4
Sets blink settings. Format is <name>[=<value>],<name>[=<value>],… The names are declared in settings.json5 from chromium project. For boolean type, use “true”, “false”, or omit ‘=<value>’ part to set to true. For enum type, use the int value of the enum value.

Devices Example

To emulate the browser behaviour on a mobile device and approximately measure the browser performance, you can import devices from k6/experimental/browser.

JavaScript
import { browser, devices } from 'k6/experimental/browser';

export const options = {
  scenarios: {
    browser: {
      executor: 'shared-iterations',
      options: {
        browser: {
          type: 'chromium',
        },
      },
    },
  },
  thresholds: {
    checks: ['rate==1.0'],
  },
};

export default async function () {
  const iphoneX = devices['iPhone X'];
  const context = browser.newContext(iphoneX);
  const page = context.newPage();

  try {
    await page.goto('https://test.k6.io/');
  } finally {
    page.close();
  }
}