> For the complete documentation index, see [llms.txt](https://docs.bugbug.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.bugbug.io/editing-tests/custom-javascript-actions.md).

# Custom JavaScript actions

Where you can run your own JavaScript in BugBug (step, assertion, JavaScript variable, Set variable), how the code is wrapped, async and timeouts, what it must return, when JavaScript variables are ev

When a built-in step can't do what you need, you can run your own JavaScript in the tested page: call an API, read `localStorage`, compute a value, or check something complex.

{% hint style="info" %}
**In short**

* You write the body of an `async` function. `await` works, and a returned Promise is awaited.
* `{{myVar}}` isn't replaced inside code. Read variables from the `variables` object. JavaScript variables from the project aren't evaluated there: they have the value `NOT_COMPUTED`.
* The return value of a **Run custom JavaScript** step is ignored. To keep a value for later steps, use a **Set variable** step with **Value** set to **Custom JavaScript**.
* A [JavaScript variable](https://docs.bugbug.io/editing-tests/variables.md#javascript-variables) is evaluated again in every step that uses it. For a value that stays the same for the whole run, such as a random email, save it once with **Set variable**.
* A custom JavaScript assertion needs an element and must return `true` or `false`.
  {% endhint %}

## Where you can use JavaScript

| Where                                                                                                                                    | Code is the body of                   | Available in the code              | Return value                                        |
| ---------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | ---------------------------------- | --------------------------------------------------- |
| [Run custom JavaScript](https://docs.bugbug.io/editing-tests/actions.md#run-custom-javascript) step (`execute`)                          | `async function(variables)`           | `variables`                        | Ignored                                             |
| [Custom JavaScript assertion](https://docs.bugbug.io/editing-tests/assertions.md#custom-javascript)                                      | `async function(selector, variables)` | `element`, `selector`, `variables` | Must be `true` (pass) or `false` (fail)             |
| [JavaScript variable](https://docs.bugbug.io/editing-tests/variables.md#javascript-variables)                                            | `async function(variables)`           | `variables`                        | Becomes the variable's value. `return` is required. |
| [Set variable](https://docs.bugbug.io/editing-tests/actions.md#set-variable) step with **Value: Custom JavaScript** (`evaluate` in YAML) | `async function(variables)`           | `variables`                        | Saved to the local variable as text                 |

## How your code runs

* **Write only the body of the function.** The editor shows the function signature above the code field, and BugBug wraps your code in that `async function` itself. Use `return` to return a value and `await` for promises. If you return a Promise, BugBug waits for it to resolve.

  ```javascript
  const response = await fetch('/api/me');
  const user = await response.json();
  return user.email;
  ```
* **The step's timeout applies.** The code can run as long as the step's [timeout](https://docs.bugbug.io/preventing-failed-tests/timeout.md) allows. If it hasn't finished by then, the step fails. Increase the step's timeout for slow requests.
* **It runs in the tested page.** You have access to `document`, `window`, `localStorage` and the page's cookies. Requests made with `fetch` are sent from the page, so the API must allow its origin (CORS).
* **Variables are in the `variables` object.** Use `variables.myVar` or `variables.testRunId`. `{{myVar}}` isn't replaced inside JavaScript code. JavaScript variables from the project or a profile aren't evaluated in `variables`: they have the text value `NOT_COMPUTED`. See [JavaScript variables in code](#javascript-variables-in-code) and [Use the variables argument](https://docs.bugbug.io/editing-tests/variables.md#use-the-variables-argument-in-your-javascript-function).
* **In YAML and the API**, a Set variable step with **Value: Custom JavaScript** has `local_variable_source: evaluate`, and **Value: Text** has `local_variable_source: value`.
* **Objects are saved as JSON.** When a JavaScript variable or Set variable returns an object or array, the value becomes its JSON text. Returning nothing saves the text `undefined`.
* **Code is checked when you save it.** Syntax errors, and code that the checker warns about, can't be saved. A JavaScript variable without `return` can't be saved either.
* **Errors fail the test.** An error thrown by your code stops the test with the `CODE_EXECUTION_ERROR` [error code](https://docs.bugbug.io/debugging-tests/error-codes.md) and shows the message. A custom JavaScript assertion that returns something other than a boolean fails with `INVALID_EXECUTION_RESULT`.

{% hint style="info" %}
JavaScript adds complexity. If you run into cookie or `Access-Control-Allow-Origin` errors, ask a developer for help or contact BugBug support. Look for a simpler solution with built-in steps first.
{% endhint %}

## When JavaScript variables are evaluated

A [JavaScript variable](https://docs.bugbug.io/editing-tests/variables.md#javascript-variables) defined in the project or a profile has no fixed value. BugBug runs its code each time a step uses `{{name}}` in one of its fields, for example the text of a Type text step or a URL. The result is used for that step only, and the next step that uses the variable runs the code again.

So a variable that returns a random value gives a different value in each step. To use the same value for the whole test run, for example a random email that you type at sign-up and check later, save it once:

1. Add a **Set variable** step with **Variable name** `email`, **Value** set to **Custom JavaScript**, and the code:

   ```javascript
   return `user-${Date.now()}@example.com`;
   ```
2. Use `{{email}}` in later steps. The value stays the same until the end of the test run.

If no page is open yet when the variable is used, for example in the URL of the first **Go to URL** step, the code runs in an isolated sandbox instead of the tested page. It has no access to the page's `document`, cookies or `localStorage` there.

### JavaScript variables in code

A JavaScript variable is evaluated only when it's used as `{{name}}` in a step field. In the `variables` object of a Run custom JavaScript step, a custom JavaScript assertion, a Set variable step or another JavaScript variable, it has the text value `NOT_COMPUTED`. This is by design.

To use its value in code, save it first:

1. Add a **Set variable** step with a **Variable name** such as `myVarValue`, **Value** set to **Text**, and the text `{{myVar}}`.
2. In later code, read `variables.myVarValue`.

## Pass a value to later steps

The return value of a **Run custom JavaScript** step is ignored. To use a computed value in later steps:

* **Use a Set variable step** with **Value** set to **Custom JavaScript**. Its result is saved to a [local variable](https://docs.bugbug.io/editing-tests/local-variables.md) that you use as `{{name}}` in later steps and as `variables.name` in later code.
* **Or use `localStorage`** to pass data between JavaScript steps and variables: save with `localStorage.setItem()` and read with `localStorage.getItem()`.

Example: save the hash of the current URL and check later that the URL still contains it.

1. Add a **Set variable** step with **Variable name** `pageHash`, **Value** set to **Custom JavaScript**, and the code:

   ```javascript
   return window.location.hash.slice(1);
   ```
2. Later, add a **URL address** assertion with **contains** `{{pageHash}}`.

## Use a project variable in code

`{{apiUrl}}` written inside the code isn't replaced. Read the value from `variables` instead:

```javascript
const response = await fetch(`${variables.apiUrl}/users`);
const users = await response.json();
return users[0].email;
```

### Example: a BugBug Inbox mailbox from a login email

An [Open inbox](https://docs.bugbug.io/editing-tests/actions.md#open-inbox) step takes only the mailbox name, the part before `@bugbug-inbox.com`. If your test has the full address in a variable, for example `loginUsername`, cut it with a **Set variable** step with **Variable name** `mailbox` and **Value** set to **Custom JavaScript**:

```javascript
return variables.loginUsername.split('@')[0];
```

Then set the Open inbox step's **Username** to `{{mailbox}}`.

## Examples

### Make an API request

Request data from your API and use it in a [JavaScript variable](https://docs.bugbug.io/editing-tests/variables.md#javascript-variables), a Set variable step or an assertion. The code runs in the browser, in the context of the tested page.

```javascript
const response = await fetch('https://reqres.in/api/users');
const json = await response.json();
return json.data[0].email; // the first user's email
```

{% hint style="info" %}
The API must allow requests from the tested page's origin (CORS). Don't use `mode: 'no-cors'`: the response would be opaque and your code couldn't read it. See the [Fetch API documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch).
{% endhint %}

| Use an API request to                                             | Example                                                               |
| ----------------------------------------------------------------- | --------------------------------------------------------------------- |
| Compare the data shown in your app with the data from the server  | Check that your currency exchange rate is up to date                  |
| Get test users and their parameters from a central test data file | Get a login and password for a random test user and skip registration |
| Get the latest item and its ID from the server                    | Check that the newest product is shown in the search results          |

### Check an element with an assertion

A custom JavaScript assertion always has an element: set its selector like for any other assertion. In the code, `element` is the found element and `selector` is its selector. Return `true` to pass or `false` to fail. The **expected value** field isn't used.

Check that an input has a specific placeholder:

1. Record a regular assertion on the input.
2. Change its type to **Custom JavaScript**.
3. Enter the code:

   ```javascript
   return element.placeholder === 'Username';
   ```

To check something that isn't tied to one element, select a stable element such as `body` and use `document` in the code.

<figure><img src="https://3168433179-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MKixgeBPbLvnD0l1eiV%2Fuploads%2F0oEE681NfPegM7oGuVdG%2FAssertion%20JS.png?alt=media&amp;token=464972a4-0ee9-4b47-85ac-56caddb6311a" alt="Custom JavaScript assertion in the step editor"><figcaption></figcaption></figure>

{% embed url="<https://youtu.be/g7CsE-WHrwQ>" %}

### Prepare the page

Set a value in `localStorage` before the next steps, for example to skip a cookie banner:

```javascript
localStorage.setItem('cookieConsent', 'true');
```

<figure><img src="https://3168433179-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-MKixgeBPbLvnD0l1eiV%2Fuploads%2FWuBVtMLXu5qAAzmZXlN8%2Fadd%20step%20js.png?alt=media&amp;token=7752a161-5eea-4dcc-9be4-8903b46fa6b4" alt="Run custom JavaScript step in the step editor"><figcaption></figcaption></figure>

## FAQ

<details>

<summary>Does Run custom JavaScript wait for a Promise?</summary>

Yes. The code is the body of an `async` function, so you can use `await`, and a returned Promise is awaited. The step's timeout limits how long the code can run.

</details>

<details>

<summary>Are {{variables}} replaced inside JavaScript code?</summary>

No. Read them from the `variables` object, for example `variables.apiUrl` or `variables.testRunId`.

</details>

<details>

<summary>How do I save a value from JavaScript for later steps?</summary>

Use a **Set variable** step with **Value** set to **Custom JavaScript** and `return` the value. Later steps use it as `{{name}}` and later code as `variables.name`. The return value of a **Run custom JavaScript** step is ignored.

</details>

<details>

<summary>How do I get a random value that stays the same for the whole test run?</summary>

Generate it in a **Set variable** step with **Value** set to **Custom JavaScript**. A JavaScript variable from the project or a profile is evaluated again in every step that uses it, so it gives a new value each time. See [When JavaScript variables are evaluated](#when-javascript-variables-are-evaluated).

</details>

<details>

<summary>Why does variables.myVar return NOT_COMPUTED?</summary>

`myVar` is a JavaScript variable. Its code runs only when a step uses `{{myVar}}` in a field, not when your code reads it from `variables`. This is by design. Save it first with a **Set variable** step with **Value** set to **Text** and the text `{{myVar}}`, and read that local variable in code. See [JavaScript variables in code](#javascript-variables-in-code).

</details>

<details>

<summary>Does a custom JavaScript assertion need a selector?</summary>

Yes. The assertion waits for the element like any other element assertion and passes it to your code as `element`. Return `true` or `false`; any other value fails the step with `INVALID_EXECUTION_RESULT`.

</details>

<details>

<summary>Can I loop in a test, for example go through pages until a row is found?</summary>

There are no loop steps. For a bounded search, repeat an [If condition](https://docs.bugbug.io/editing-tests/conditional-logic-if-else.md) a fixed number of times: "if the row is not visible, click **Next page**". Or find the row in code: a **Set variable** step with **Value** set to **Custom JavaScript** can call your API and return the page number or ID you need.

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.bugbug.io/editing-tests/custom-javascript-actions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
