Browser Reference

The browser object is available within Browser Scripts and provides programmatic control over headless web browsers. With this object, you can use JavaScript to control browser actions like clicking, typing, navigation, and form submission with full access to the DOM.

Important: The browser object is only available when running Browser Scripts with Browser Bots. If you try to use the browser object in a Protocol Script, it will be undefined and cause errors.

Understanding Browser Automation in Loadster

In Loadster, Browser Scripts control real headless Chrome browsers to simulate user interactions. While regular browser steps provide a visual, step-by-step approach to building user flows, the browser object in code blocks gives you programmatic control over the same functionality.

The browser object provides methods for all common browser actions including navigation, element interaction, form submission, and window management. All browser methods are synchronous - no need for await or promise chains - and each bot maintains its own isolated browser instance with separate sessions, cookies, and DOM state.

Browser automation is ideal for testing complex web applications that rely heavily on JavaScript, single-page applications, or scenarios requiring realistic user behavior patterns. Each bot’s browser instance maintains full session state, cookies, and local storage just like a real user’s browser would.

Browser Control vs. Page Content Access

The browser object provides external control over the browser - clicking elements, typing text, navigating pages, and configuring browser settings. However, the browser object does not have direct access to JavaScript variables, functions, or objects that exist inside the web page.

To access page content, DOM elements, or JavaScript variables within the browser, you need to use:

  • browser.eval() - Execute JavaScript code inside the browser and return results
  • Evaluate Blocks - Browser script steps that run JavaScript in the browser context

Think of it this way: the browser object controls the browser from the outside (like a user would), while browser.eval() lets you run code inside the browser’s JavaScript environment.

Note: Element selectors throughout the browser API use CSS selector syntax - the same as document.querySelector(). Browser actions automatically wait for elements to be ready before proceeding.

Browser Navigation and Page Actions

These methods control page navigation and basic browser actions. They form the foundation of browser automation by allowing you to navigate between pages and interact with the browser window itself.

browser.navigate(url)

Navigate to a specific URL.

browser.navigate('https://petstore.loadster.app');

// Navigate to dynamic URLs using variables
browser.navigate(`https://example.com/user/${bot.getVariable('userId')}`);

Parameters:

  • url - The URL to navigate to

This method loads a new page in the browser, triggering all associated network requests, JavaScript execution, and DOM rendering. It’s equivalent to typing a URL into the browser’s address bar and pressing Enter.

Note: All browser methods are synchronous - no need for await or promise chains.

browser.click(selector, options)

Click on an element matching the CSS selector.

browser.click('button.login-button');

// Click with options
browser.click('#cookie-warning', { timeout: 3000, silent: true });

Parameters:

  • selector - CSS selector to identify the element to click
  • options - Optional configuration object:
    • timeout - Maximum time to wait for element in milliseconds (default: Action Timeout from Settings)
    • silent - If true, don’t fail the test if element not found (default: false)

This method performs a mouse click on the first element matching the selector. It waits for the element to be visible and clickable before performing the action, and triggers all associated click events and JavaScript handlers.

Note: Use browser.screenshot() for debugging when elements don’t behave as expected during testing.

browser.type(selector, text, options)

Type text into an input element.

browser.type('.username', 'sloth');
browser.type('.password', 'chunk');

// Type with custom delay
browser.type('.greeting', 'Hello', { delay: 0 }); // Instant typing
browser.type('.greeting', 'Hello', { delay: 1250 }); // 1.25s between keystrokes

Parameters:

  • selector - CSS selector to identify the input element
  • text - The text to type into the element
  • options - Optional configuration object:
    • delay - Delay between keystrokes in milliseconds (default: 0)
    • timeout - Maximum time to wait for element in milliseconds (default: Action Timeout from Settings)
    • silent - If true, don’t fail the test if element not found (default: false)

This method types text into form fields, text areas, or any element that accepts keyboard input. It simulates realistic keyboard input by sending individual keystrokes and triggering all associated input events.

browser.hover(selector)

Hover over an element.

browser.hover('.menu');
browser.click('.menu li:first-child');

Parameters:

  • selector - CSS selector to identify the element to hover over

This method moves the mouse cursor over an element, triggering hover states and mouse events. It’s commonly used to reveal dropdown menus, tooltips, or other hover-triggered interface elements.

browser.selectByIndex(selector, index)

Select an option from a select element by its position.

Given this HTML:

<select name="countries">
  <option value="US">United States</option>
  <option value="CA">Canada</option>
  <option value="HR">Croatia</option>
</select>
browser.selectByIndex('select[name=countries]', 1);
browser.selectByIndex('select[name=countries]', 0);

Parameters:

  • selector - CSS selector to identify the select element
  • index - Zero-based index of the option to select

This method selects an option from a dropdown menu by its position in the list. Index 0 is the first option, index 1 is the second, and so on. This is useful when you know the position of the option you want to select.

browser.selectByValue(selector, value)

Select an option from a select element by its value attribute.

Given this HTML:

<select name="countries">
  <option value="US">United States</option>
  <option value="CA">Canada</option>
  <option value="HR">Croatia</option>
</select>
browser.selectByValue('select[name=countries]', 'HR');
browser.selectByValue('select[name=countries]', 'US');

Parameters:

  • selector - CSS selector to identify the select element
  • value - Value attribute of the option to select

This method selects an option from a dropdown menu by matching its value attribute. This is the most reliable method when you know the option’s value, as it doesn’t depend on the displayed text or position.

browser.selectByText(selector, text)

Select an option from a select element by its visible text.

Given this HTML:

<select name="countries">
  <option value="US">United States</option>
  <option value="CA">Canada</option>
  <option value="HR">Croatia</option>
</select>
browser.selectByText('select[name=countries]', 'Croatia');
browser.selectByText('select[name=countries]', 'United States');

Parameters:

  • selector - CSS selector to identify the select element
  • text - Visible text content of the option to select

This method selects an option from a dropdown menu by matching its displayed text. This is useful when you want to select based on what the user sees, but be aware that text can change with localization or updates.

browser.chooseFiles(selector, files)

Choose files for a file input element.

browser.chooseFiles('input[type=file]', [{
    name: 'lolcat',
    contentType: 'image/jpeg',
    contentBase64: 'UklGRuZ/AABXRUJQVlA4INp/AABwrAGdASr0AQACPjkYi0QiIaET'
}]);

Parameters:

  • selector - CSS selector to identify the file input element
  • files - Array of file objects with properties:
    • name - The filename
    • contentType - MIME type of the file
    • contentBase64 - Base64-encoded file content

This method simulates selecting files in a file upload dialog. It’s useful for testing file upload functionality in web applications.

Note: The file contents are stored as part of the Loadster script itself, since bots will not have direct access to the user’s filesystem at test runtime. You must provide the file data as base64-encoded content when creating the script.

browser.keyboard.press(key)

Press individual keys on the keyboard.

browser.keyboard.press('ArrowUp');
browser.keyboard.press('X');
browser.keyboard.press('Enter');

Parameters:

  • key - The key to press (e.g., ‘Enter’, ‘ArrowUp’, ‘Tab’, ‘Escape’)

This method simulates pressing individual keyboard keys, including special keys like arrows, Enter, Tab, and function keys. It’s useful for keyboard navigation and shortcuts.

Key names follow the W3C UI Events KeyboardEvent key values specification. Common keys include: ‘Enter’, ‘Tab’, ‘Escape’, ‘ArrowUp’, ‘ArrowDown’, ‘ArrowLeft’, ‘ArrowRight’, ‘Backspace’, ‘Delete’, ‘Home’, ‘End’, ‘PageUp’, ‘PageDown’, and individual characters like ‘a’, ‘A’, ‘1’, etc.

browser.screenshot(full)

Take a screenshot of the current page.

browser.screenshot();

// Take a full page screenshot
browser.screenshot(true);

// Take a viewport-only screenshot
browser.screenshot(false);

Parameters:

  • full - Boolean to control screenshot scope (default: false)
    • true - Capture the entire page including content below the fold
    • false - Capture only the current browser viewport

This method captures a screenshot of the current browser page, which is useful for debugging test failures or documenting the state of the page during test execution.

Note: Screenshots are particularly helpful for debugging when tests don’t behave as expected, allowing you to see exactly what the browser was displaying at the time of failure.

Browser Timing and Synchronization

These methods help you wait for specific conditions or page states before proceeding. They’re essential for handling dynamic content, AJAX requests, and ensuring reliable test execution timing.

browser.waitFor(selector, state, options)

Wait for an element to be in a specific state.

browser.waitFor('.spinning-overlay', 'hidden');
browser.waitFor('.spinning-overlay', 'visible');
browser.waitFor('.spinning-overlay', 'attached');
browser.waitFor('.spinning-overlay', 'detached');

// With timeout and silent options
browser.waitFor('.spinning-overlay', 'hidden', { timeout: 5000, silent: true });

Parameters:

  • selector - CSS selector to identify the element to wait for
  • state - The state to wait for: ‘visible’, ‘hidden’, ‘attached’, or ‘detached’
  • options - Optional configuration object:
    • timeout - Maximum time to wait in milliseconds (default: Action Timeout from Settings)
    • silent - If true, don’t fail the test if condition not met (default: false)

This method waits for elements to appear, disappear, or change visibility state. It’s essential for handling dynamic content that loads asynchronously or animations that need to complete before proceeding.

browser.waitForUrl(url, options)

Wait for a specific URL to be loaded.

browser.waitForUrl('https://example.com/success');
browser.waitForUrl('https://example.com/success', { timeout: 5000, silent: true });

Parameters:

  • url - The URL to wait for
  • options - Optional configuration object:
    • timeout - Maximum time to wait in milliseconds (default: Navigation Timeout from Settings)
    • silent - If true, don’t fail the test if URL not reached (default: false)

This method waits for the browser to navigate to a specific URL, useful for confirming that form submissions, redirects, or navigation actions have completed successfully.

Browser JavaScript Execution

These methods allow you to execute JavaScript code directly in the browser context, giving you access to the DOM and browser APIs from within your test code.

browser.eval(code)

Execute JavaScript code inside the browser and return the result.

let invoiceCount = browser.eval("document.querySelectorAll('.invoice').length");

if (invoiceCount > 0) {
    browser.click('.invoice .archive-button');
} else {
    console.log('There are no more invoices!');
}

Parameters:

  • code - JavaScript code to execute in the browser context

This method executes JavaScript code inside the browser’s context, allowing you to interact with the DOM, access browser APIs, and extract data that might not be available through other browser methods. The code runs in the actual browser environment, not in the test script context.

Note: The browser object itself runs outside the browser environment and only provides external control. Use browser.eval() to execute JavaScript inside the browser when you need access to the DOM, JavaScript variables, or browser APIs that exist within the page.

Browser Window and Tab Control

These methods control browser windows and tabs, allowing you to simulate multi-tab browsing behavior and manage complex user scenarios that span multiple browser windows.

browser.setViewportSize(width, height)

Resize the browser viewport.

browser.setViewportSize(1800, 1200);

Parameters:

  • width - Viewport width in pixels
  • height - Viewport height in pixels

This method sets the size of the browser viewport, which affects how responsive layouts render and can trigger different CSS media queries or JavaScript responsive behavior.

browser.listWindows()

List all browser windows/tabs.

const windows = browser.listWindows();

This method returns an array of all open browser windows/tabs, which you can use to determine how many windows are open and manage them programmatically.

browser.openWindow()

Open a new window/tab and make it active.

browser.openWindow();

This method opens a new browser window or tab and automatically switches focus to it. The new window starts with a blank page and becomes the active window for subsequent browser actions.

browser.getActiveWindow()

Get the currently active window/tab index.

const activeWindow = browser.getActiveWindow(); // 0, 1, 2...

This method returns the zero-based index of the currently active window or tab, which helps you track which window you’re currently controlling.

browser.setActiveWindow(index)

Focus a different browser window/tab.

browser.setActiveWindow(0); // the bot's original tab
browser.setActiveWindow(1); // the first opened tab
browser.setActiveWindow(2); // and so on...

Parameters:

  • index - Zero-based index of the window to activate

This method switches focus to a different browser window or tab. All subsequent browser actions will be performed in the newly active window.

browser.closeWindow(index)

Close a browser window/tab.

browser.closeWindow(1);

Parameters:

  • index - Zero-based index of the window to close

This method closes a specific browser window or tab. If you close the currently active window, focus will automatically switch to another open window.

Browser Headers and User Agent

These methods configure browser headers and user agent strings, allowing you to customize how your bot identifies itself to servers and set custom headers for requests.

browser.setUserAgent(userAgent)

Set a custom User-Agent header.

browser.setUserAgent('Loadster/Speedway');

// Or pretend to be a normal, non-headless browser
browser.setUserAgent('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36');

Parameters:

  • userAgent - The User-Agent string to send with requests

This method changes the User-Agent header that the browser sends with all requests. This can be useful for testing how your application responds to different browsers or for avoiding detection as a headless browser.

Note: Configuration methods like user agent should be called before navigation for best results.

browser.setGlobalHeader(name, value)

Set a global request header for all domains.

browser.setGlobalHeader('X-Loadster', 'true');
browser.setGlobalHeader('User-Agent', 'Custom Bot 1.0');

Parameters:

  • name - The header name
  • value - The header value

This method sets a header that is sent with all requests to any domain. Global headers are useful for identifying load test traffic or adding consistent metadata across all requests.

Note: Setting custom headers may disable browser cache in some cases.

browser.removeGlobalHeader(name)

Remove a global request header.

browser.removeGlobalHeader('X-Loadster');
browser.removeGlobalHeader('User-Agent');

Parameters:

  • name - The header name to remove

This method removes a previously set global header from all future requests. Useful for changing test behavior or removing headers that are no longer needed.

browser.setHostHeader(host, name, value)

Set a request header for a specific domain.

browser.setHostHeader('example.com', 'X-Loadster', 'true');
browser.setHostHeader('api.example.com', 'Authorization', 'Bearer token123');

Parameters:

  • host - The domain name to apply the header to
  • name - The header name
  • value - The header value

This method sets a header that is sent only to requests for a specific domain. This is useful for setting authentication tokens or other headers that should only be sent to particular APIs or services.

Note: Setting custom headers may disable browser cache in some cases.

browser.removeHostHeader(host, name)

Remove a request header for a specific domain.

browser.removeHostHeader('example.com', 'X-Loadster');
browser.removeHostHeader('api.example.com', 'Authorization');

Parameters:

  • host - The domain name to remove the header from
  • name - The header name to remove

This method removes a previously set header for a specific domain. This provides fine-grained control over which headers are sent to which domains during your test.

Browser Resource and Request Control

These methods control which resources the browser loads, allowing you to optimize test performance by blocking unnecessary requests or simulate network conditions.

browser.blockRequestsIfUrlContains(substring)

Block requests to URLs containing a specific substring.

browser.blockRequestsIfUrlContains('analytics.js');
browser.blockRequestsIfUrlContains('.jpg');
browser.blockRequestsIfUrlContains('cdn.example.com');

Parameters:

  • substring - String that must be present in the URL for the request to be blocked

This method prevents the browser from loading resources whose URLs contain the specified substring. It’s useful for blocking analytics scripts, images, or third-party resources that aren’t essential for your test and may slow down execution.

Note: Blocking resources may disable browser cache and can affect how the page behaves if the blocked resources are essential for functionality.

These methods control browser cookies, allowing you to set authentication tokens, session identifiers, or other cookie-based data that your application requires.

browser.addCookie(options)

Add a cookie to the browser.

// Add a cookie for a specific URL
browser.addCookie({ 
    url: 'https://example.com', 
    name: 'automated-testing', 
    value: 'true' 
});

// Add a cookie for a domain and path
browser.addCookie({ 
    domain: 'example.com', 
    path: '/', 
    name: 'automated-testing', 
    value: 'true' 
});

// Add a cookie with expiration and security attributes
browser.addCookie({ 
    url: 'https://example.com', 
    name: 'automated-testing', 
    value: 'true', 
    expires: 86400, 
    httpOnly: true, 
    secure: true, 
    sameSite: true 
});

Parameters:

  • options - Cookie configuration object with properties:
    • url - URL the cookie applies to (alternative to domain/path)
    • domain - Domain the cookie applies to
    • path - Path the cookie applies to (default: ‘/’)
    • name - Cookie name
    • value - Cookie value
    • expires - Expiration time in seconds from now
    • httpOnly - Whether cookie is HTTP-only
    • secure - Whether cookie requires HTTPS
    • sameSite - SameSite attribute for the cookie

This method adds cookies to the browser’s cookie store, which can be used to simulate logged-in users, set preferences, or provide any cookie-based data your application needs.

Browser Authentication

These methods configure browser authentication settings for HTTP Basic Auth, NTLM, and other authentication schemes that browsers handle automatically.

browser.setHttpAuthentication(username, password)

Set HTTP Basic or NTLM authentication credentials.

browser.setHttpAuthentication('myUsername', 'myPassword');

Parameters:

  • username - Authentication username
  • password - Authentication password

This method configures automatic authentication for HTTP Basic Auth or NTLM authentication challenges. The browser will automatically provide these credentials when prompted by the server.

Browser Dialog and Popup Control

These methods control how the browser responds to JavaScript dialogs, alerts, and confirmation prompts that might appear during testing.

browser.setDialogConfirmation(confirm)

Set how to respond to browser confirmation dialogs.

browser.setDialogConfirmation(true);  // Answer "OK" to confirm() dialogs
browser.setDialogConfirmation(false); // Answer "Cancel" to confirm() dialogs

Parameters:

  • confirm - Boolean indicating whether to accept (true) or cancel (false) confirmation dialogs

This method sets how the browser automatically responds to JavaScript confirm() dialogs. Without setting this, confirmation dialogs would block test execution.

Browser Geolocation

These methods control the browser’s geolocation API, allowing you to simulate users from different geographic locations or test location-based features.

browser.enableGeolocation(latitude, longitude)

Enable geolocation at a specific latitude and longitude.

browser.enableGeolocation(40.7128, -74.0060); // New York City

Parameters:

  • latitude - Latitude coordinate
  • longitude - Longitude coordinate

This method enables the browser’s geolocation API and sets it to report a specific location. This is useful for testing location-based features or services that depend on user location.

Note: Geolocation should be configured before navigation for best results.

browser.disableGeolocation()

Disable geolocation permissions.

browser.disableGeolocation();

This method disables the browser’s geolocation API, simulating a user who has denied location permissions or is using a browser without geolocation support.