# Browser Scripts

> Loadster's browser scripts control real headless Chrome browsers. They're the most realistic way to test complex web applications.

Source: https://loadster.com/manual/browser-scripts/

Browser scripts automate headless Chrome web browsers. They are executed by Browser Bots.

Real browsers are the best way to [load test](https://loadster.com/use-cases/load-testing/) the full stack of your application, including client-side 
rendering, or when [protocol scripting](https://loadster.com/manual/protocol-scripts/) is too tricky to work with your site.

If you've worked with browser automation tools like Selenium, Puppeteer, or Playwright, you already understand the
concept of browser scripts. Loadster's implementation is based on Playwright.

## Action Steps

Each step in your browser script represents an action taken by the user in their web browser. A browser script could
have just a single step (loading a page) or many (navigating, clicking, typing, waiting, etc).

You can also write your own JavaScript to be executed on the page or in Loadster's own environment.

Loadster always executes browser steps sequentially.

### Navigate To URL

A navigate step is like putting a URL into the browser's location bar. If this is the initial step in your script,
it opens a fresh browser context and navigates to that location. If there were previous steps, this step leaves the
current location and navigates to a new one.

### Click On Element

A click step clicks an element on the page.

You specify the element with a [locator](#locating-elements). If the element is not found on the page initially,
the bot will automatically wait a while for the element to appear.

Click steps are useful for clicking on links or buttons, just like a human user might do.

### Hover On Element

A hover step moves the mouse over an element on the page. It works just like a click step, using a
[locator](#locating-elements) to find the element. Most of the time you won't need to use a hover step, since
clicking on an element will also move the mouse over it, but certain sites have hover menus and other features
that expose other elements when an element is hovered.

### Enter Text Into Field

A type step simulates typing text into an input element, such as a text field or textarea.

You specify the input element with a [locator](#locating-elements). If the element is not found on the page
initially, the bot will automatically wait a while for the element to appear before typing.

Typing into fields is necessary when your script needs to log in, fill out a form, and so on.

### Select From Dropdown

A select step can choose an option from an HTML `select` element on the page.

You specify the select element with a [locator](#locating-elements). If the select element is not found on the
page initially, the bot will automatically wait a while for it to appear.

You'll also need to specify which of the options to select from the list. The option can be specified by name,
value, or index. For example, let's say your select tag has the following HTML markup:

```
<select name="countries">
  <option value="CR">Costa Rica</option>
  <option value="HR">Croatia</option>
  <option value="CU">Cuba</option>
</select>
```

If you wanted to select Croatia, your step could specify `CR` to select by value, `"Croatia"` with double quotes
to select by name, or `[1]` with square brackets to select by index.

You can also select elements programmatically in a [Code Block](https://loadster.com/manual/code-blocks/#browser).

### Add Files To Input

To interact with a file input element, like `<input type="file"/>`, use a Files step.
Executing a files step is equivalent to clicking on the file picker, opening up the file chooser dialog, and choosing
a file from your local filesystem in a real browser.

When you add a files step to your script, you get to specify what file(s) it should use. Your local file's content
becomes *part of your script*, so when the bots later run the script out on the engine, they have the file
data and no longer need access to your local filesystem.

## Locating Elements

Most action steps – click, hover, type, select, files, and wait-for – need to target a specific element on the page.
Loadster's locators are based on [Playwright's locators](https://playwright.dev/docs/locators), which are flexible
ways to describe which element you mean.

You can chain multiple locators together to narrow down to a single element. Each locator refines the match from
the previous one. If more than one element still matches at the end of the chain, the bot picks the first by default,
so it's usually a good idea to chain a `First`, `Last`, or `Nth` modifier on the end when you expect multiple matches.

### Selector

A CSS or XPath selector like `#username`, `.btn-primary`, or `form input[name='email']`. This is the most flexible
locator and works well when you can identify an element by its HTML attributes. Longer selectors like
`form.registration input[type='text']` are also supported.

### Label

Matches a form field by its associated `<label>` text. A label that reads "Email address" will match the input
it's linked to. Labels tend to stay stable even when class names or IDs change, so this is usually a good choice
for form fields.

### Text

Matches an element by its visible text content, like the text inside a button or a link. Useful for elements that
don't have stable IDs but show consistent text.

### Alt Text

Matches an element by its `alt` attribute. Most often used for images, where the alt text describes the image.

### Title

Matches an element by its `title` attribute (the tooltip that shows up on hover).

### Test ID

Matches an element by its `data-testid` attribute. Test IDs are usually added specifically for automated testing,
so they're typically the most stable kind of locator and don't change with design tweaks.

### Placeholder

Matches an input by its `placeholder` text – the hint text that's shown inside an empty field.

### Role

Matches an element by its ARIA role (like `button`, `link`, or `textbox`), and optionally by its accessible name.
This is helpful for testing accessibility and works well for components that use ARIA attributes correctly.

### iFrame

If the element you want is inside an `<iframe>`, start the chain with an iFrame locator to enter the frame, then
add another locator after it to find the element within.

### Filter

Refines an earlier match by text content or visibility. Useful when several elements match an earlier locator and
you want to narrow down by something the earlier locator can't express on its own.

### First, Last, Nth

When multiple elements still match the chain so far, these modifiers pick a specific one – the first match, the
last match, or the nth match (zero-indexed).

## Waiting Steps

Wait steps cause the bot to pause for a set amount of time, or until an element on the page has a certain state.
This makes your test more realistic.

In some cases you might also need to wait for an element to appear on the page or for a progress overlay to disappear.

### Wait

A wait step makes the bot pause temporarily, much like a real user might do when viewing a page and before
navigating to the next page.

Waiting between actions like a real user would makes a script more realistic.

Wait steps can be skipped over in certain situations, like when you're running the script as a monitor or playing
the script in Fast Play mode in the script editor.

### Wait For

Instead of waiting for a fixed amount of time, you can wait for a certain element on the page to be in a certain state.
The element can be any [locator](#locating-elements), and the states are:

- `visible` - The element exists in the DOM and is not transparent, hidden, or behind another element.
- `hidden` - The element exists in the DOM, but is hidden by CSS or obscured by another element.
- `attached` - The element exists in the DOM.
- `detached` - The element has been removed from the DOM.

If the element never achieves the desired state, the step will eventually time out with an error.

## Advanced Steps

### Code Block

A code block lets you write your own JavaScript code, which is executed in Loadster's environment,
not in the browser. Code blocks are meant for implementing your own looping, conditional logic, and control flow in your
script.

In code blocks, you have access to modern ECMAScript syntax like the `() => {}` arrow functions and `const` and `let`,
as well as common parsing functionality like `JSON.parse(str)` and `XML.parse(str)`.

Code blocks are very powerful, and in fact you could write an entire script in a code block.
Read more about them in the [Code Blocks](https://loadster.com/manual/code-blocks/) section.

Since the code block isn't executed *in* the browser, it doesn't have direct access to the variables
in the browser's context, such as `window` or `document`. Take a look at
[Evaluate Blocks](https://loadster.com/manual/browser-scripts/evaluate-blocks/) if you need to access those.

### Evaluate JavaScript

Browser bots can even evaluate arbitrary JavaScript *inside* the automated browser. This is great if you need to do special
on-page automation at a more granular level than you can accomplish with individual steps. This is a big topic, and
we cover a few of the possibilities in [Evaluate Blocks](https://loadster.com/manual/browser-scripts/evaluate-blocks/).

## Debugging

### Scrape

A scrape step captures the entire DOM from your browser in real time. It's basically like "View Source".
This is helpful when you are scripting, since it allows you to see what elements exist on the page.

### Screenshot

When scripting, you can take a screenshot of the bot's browser at any time. It's often helpful
to see what the bot is seeing.

Taking a screenshot can be CPU intensive for Loadster's engines, but has no impact on your server.

### Comment

A comment step is a way to add a comment to your script. It's not really a step, but it's useful for
documenting your script. Bots ignore comments – they're just there for you and other humans.


## Recording a Browser Script

Recording a script from your web browser is often the easiest way to get started, and it works the same way for browser
scripts as it does for [protocol scripts](https://loadster.com/manual/protocol-scripts/).

### Installing the Loadster Recorder browser extension

To record your browser traffic and make a Loadster script, you'll need the free
[Loadster Recorder for Chrome](https://chrome.google.com/webstore/detail/loadster-recorder/bkhfnmahbfjemfpgehoolkhhdhbidaan)
or [Loadster Recorder for Firefox](https://addons.mozilla.org/en-US/firefox/addon/loadster-recorder/).

After you've installed the extension in your browser, expand it by clicking the extension icon in your browser's toolbar.
You can toggle the switch to enable or disable sharing your browsing activity with Loadster.

The browser extension is open source and you can review the source code on
[GitHub](https://github.com/loadster/loadster-browser-extension).

### Recording your browser activity

To start recording, open a new or existing browser script and hit **Record**. Loadster will start communicating with the
Loadster Recorder browser extension.

Enter the URL of the first page you want to record.

When you hit **Start Recording**, Loadster will open a new browser tab to that location.
Whatever you do in that browser tab will be recorded as an event and show up in the recording log.
Traffic in your other browser tabs is not recorded.

Click **Stop Recording** when you're finished.

Immediately after you stop the recording, you'll see a list of all of the recorded browser actions.
You can choose to exclude any actions that you don't want in your script.

## Editing Browser Scripts

You probably already noticed that you can add, edit, drag, and remove steps to edit your script.

Here are a few things that work for all kinds of steps:

* **Add a step** by clicking the toolbar button with the relevant step type.
* **Select a step or steps** by clicking (or shift-clicking) in a neutral area of a step, such as the left handle.
* **Copy and paste steps** by selecting them and using your ordinary keyboard shortcuts (control-c/v or command-c/v). You can even copy and paste them between scripts.
* **Duplicate a step** by hovering and clicking on the duplicate icon on the right-hand side of the step.
* **Delete a step** by hovering and clicking on the delete icon on the right-hand side of the step.
* **Disable or enable a step** by hovering and clicking the toggle icon on the right-hand side of the step. Disabled steps remain in your script but are not played (like commenting them out).
* **Drag to reorder steps** by clicking in a neutral area, such as the left handle, and dragging to a new position.

Aside from that, each type of step has its own attributes that you can edit separately.

### Editing wait steps

Wait steps are simple. They simply make the bot pause execution of the script for a certain number of
seconds.

To change the duration, click the number of seconds, and enter a new number.

Having realistic wait times is important. You should try to make your scripts run at the same cadence a real user would.
If your wait times are unrealistic, your load test results related to the number of concurrent users will be too.

### Editing browser steps

Most of the other steps, like navigate steps and click steps, allow you to specify which element to act upon with a
[locator](#locating-elements). Some steps, like type steps, also accept another parameter, which is the text to be
entered into the field.

You can use [variables and expressions](https://loadster.com/manual/variables-and-expressions/) to inject dynamic data into these fields.

## Viewing Trace Details

When you play a browser script or drill down into a monitor cycle, you can view traces that show detailed information
about what happened during each navigation.

### Resource Waterfall

The trace waterfall shows all the resources loaded by the page (HTML, CSS, JavaScript, images, API calls, etc.) with
timing bars that show when each resource was requested and how long it took. This helps you identify slow resources,
blocking requests, and loading bottlenecks.

### Request & Response Headers

You can expand any resource in the waterfall to inspect the HTTP request and response headers that were sent and
received. This is useful for debugging caching behavior, content negotiation, authentication headers, CORS issues,
and other HTTP-level details without needing a separate tool.

### Disable Web Security

If the site you're testing has restrictive CORS policies that interfere with browser script execution, you can enable
the *Disable Web Security* option in the script settings. This tells the browser to relax same-origin restrictions,
which can be helpful when your scripts need to interact with cross-origin resources that would otherwise be blocked.

Use this setting only when necessary, as it changes the browser's security behavior and may not reflect how real
users experience your site.

## Validation in Browser Scripts

Unlike protocol scripts, which have [validation rules](https://loadster.com/manual/protocol-scripts/validation-rules/), browser scripts
do not have a special construct for validation. Instead, you can perform custom validation by throwing an error from
a [code block](https://loadster.com/manual/code-blocks/) or [eval block](https://loadster.com/manual/browser-scripts/evaluate-blocks/).


