---
updatedAt: 2026-08-17T14:00:39.000Z
agentTools:
  siteIndex: https://documentation.bloomreach.com/llms.txt
  projectIndex: https://documentation.bloomreach.com/engagement/llms.txt
---

# Campaigns and personalization

## showWebLayer()

In addition to configuring rules for showing weblayers in Marketing App you can also trigger a weblayer manually by calling the `showWebLayer()` function.

### Arguments

| Name                    | Value                   | Description                                                                 |
| :---------------------- | :---------------------- | :-------------------------------------------------------------------------- |
| BannerId **(Required)** | String                  | ID of your banner                                                           |
| Parameters              | Object                  | Pass custom parameters to your banner                                       |
| NoHiding                | Boolean (default false) | Keep other layers visible?                                                  |
| OnSuccess callback      | Function                | Execute custom function after successfully receiving banner from Marketing |

### Examples

Show a weblayer by ID:

```javascript
exponea.showWebLayer('5c8f6c6b48092d00121cf959');
```

Show a weblayer, pass custom parameters, and register a callback:

```javascript
exponea.showWebLayer(
  '5c8f6c6b48092d00121cf959',
  {
    myCustomValue: 12 // accessible in the weblayer as {{ params.myCustomValue }}
  },
  true,
  function(){
    // called after the web ayer is shown
  }
);
```

<Callout icon="📘" theme="info">
  ### Note

  You can still use the older function `showBanner()` to achieve the same result.
</Callout>

When calling `showWebLayer`, the grouping policy and some of the settings from the weblayer setup are ignored:

* **Ignored parameters**: `schedule`, `showOn`, `target devices`
* **Applied parameters**: `display`, `audience`

## getRecommendation()

Get personalized recommendations from your Marketing recommendation model.

### Arguments

| Name                   | Value  | Description            |
| :--------------------- | :----- | :--------------------- |
| Options **(Required)** | Object | Recommendation options |

### Options

<Table align={["left","left","left"]}>
  <thead>
    <tr>
      <th>
        Name
      </th>

      <th>
        Value
      </th>

      <th>
        Description
      </th>
    </tr>
  </thead>

  <tbody>
    <tr>
      <td>
        recommendationId **(Required)**
      </td>

      <td>
        String
      </td>

      <td>
        ID of your recommendation model.
      </td>
    </tr>

    <tr>
      <td>
        fillWithRandom
      </td>

      <td>
        Boolean
      </td>

      <td>
        If true, fills the recommendations with random items until size is reached. This is utilized when models cannot recommend enough items.
      </td>
    </tr>

    <tr>
      <td>
        callback **(Required)**
      </td>

      <td>
        Function
      </td>

      <td>
        Handle data returned from recommendation model.
      </td>
    </tr>

    <tr>
      <td>
        size
      </td>

      <td>
        Number
      </td>

      <td>
        Specifies the upper limit for the number of recommendations to return. Defaults to 10.
      </td>
    </tr>

    <tr>
      <td>
        items
      </td>

      <td>
        Object
      </td>

      <td>
        If present, the recommendations are related not only to a customer, but to products with IDs specified in this array. Item IDs from catalog used to train the recommendation model need to be used. Input product IDs in a dictionary as \{product_id: weight\}, where the value weight determines the preference strength for the given product (bigger number = higher preference).

        Example:<br />`json
        {"product_id_1": 1, "product_id_2": 2,}
        `
      </td>
    </tr>

    <tr>
      <td>
        catalogFilter
      </td>

      <td>
        Array of Objects
      </td>

      <td>
        Adds additional constrains to catalog when retrieving recommended items.

        Can only be applied to fields marked as `searchable`. It is not possible to use `item_id` as a filter

        | Data Types | Operators                                                                                             |
        | ---------- | ----------------------------------------------------------------------------------------------------- |
        | Common     | is set, is not set, has value, has no value                                                           |
        | Strings    | equals, does not equal, in, not in, contains, does not contain                                        |
        | Numbers    | equal to, in between, less than, greater than                                                         |
        | Boolean    | is true, is false                                                                                     |
        | Dates      | more than, less than, matches range, matches current day, matches current month, matches current year |

        _Example:_<br />`json [
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": "jacket"
                        }
                    ],
                    "operator": "contains",
                    "type": "string"
                },
                "property": "name"
            },
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": ""
                        }
                    ],
                    "operator": "has value",
                    "type": "string"
                },
                "property": "description"
            },
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": "SUPER BRAND"
                        }
                    ],
                    "operator": "equals",
                    "type": "string"
                },
                "property": "brand"
            },
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": "Women"
                        }
                    ],
                    "operator": "equals",
                    "type": "string"
                },
                "property": "gender"
            },
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": 20
                        },
                        {
                            "type": "constant",
                            "value": 100
                        }
                    ],
                    "operator": "in between",
                    "type": "number"
                },
                "property": "price"
            },
            {
                "constraint": {
                    "operands": [
                        {
                            "type": "constant",
                            "value": 0
                        }
                    ],
                    "operator": "greater than",
                    "type": "number"
                },
                "property": "stock_level"
            }
        ]
        `
      </td>
    </tr>

    <tr>
      <td>
        catalogAttributesWhitelist
      </td>

      <td>
        Array of Strings
      </td>

      <td>
        Returns only specified attributes from catalog items. If empty or not set, returns everything.

        _Example:_<br />`["item_id", "title", "link", "image_link"]`
      </td>
    </tr>

    <tr>
      <td>
        strategy
      </td>

      <td>
        String
      </td>

      <td>
        If specified, overrides the predefined value of the recommendation. Corresponds with the setting in the application. Can be one of `'winner'` or `'mix'`.
      </td>
    </tr>

    <tr>
      <td>
        categoryNames
      </td>

      <td>
        Array of Strings
      </td>

      <td>
        Returns only specified categories.

        (Required for [Metric based category](https://documentation.bloomreach.com/engagement/docs/recommendation-templates#section-metric-based-category) engine; when passing to Metric based category, the list is limited to 10)

        _Example:_<br />`["t-shirt", "jeans"]`<br />or<br />` ["125", "14", "2"]`
      </td>
    </tr>
  </tbody>
</Table>

### Examples

Display a recommendation model on the page:

```html
<div id='recommendations'>
  Preparing recommendations just for you...
</div>
<script>
  var options = {
    recommendationId: '5a7c4dfefb6009323d4c7311',
    size: 5,
    callback: onRecommendationsLoaded,
    fillWithRandom: true,
  };
  exponea.getRecommendation(options);

  function onRecommendationsLoaded(data) {
    if (data && data.length > 0) {
      var element = document.getElementById('recommendations');
      var ul = document.createElement('ul');
      element.appendChild(ul);
      for (var i = 0; i < data.length; i++) {
        var item = data[i];
        var li = document.createElement('li'),
            a = document.createElement('a');
        a.id = item.item_id;
        a.setAttribute('href', item.url);
        a.innerText = a.textContent = item.title;
        li.appendChild(a);
        ul.appendChild(li);
      }
    } else {
      document.getElementById('recommendations').innerHTML =
        'Nothing could be recommended for you!';
    }
  }
</script>
```

## getAbTest()

Runs an [A/B test](https://documentation.bloomreach.com/engagement/docs/ab-tests) and returns the result.

### Arguments

| Name                    | Value    | Description                                         |
| :---------------------- | :------- | :-------------------------------------------------- |
| Name **(Required)**     | String   | Name of your A/B test                               |
| Variants **(Required)** | Object   | A/B test options and probabilities                  |
| Callback                | Function | Do you tested stuff accordingly to returned variant |

### Examples

```javascript
exponea.getAbTest(
  'Add to cart button A/B test', 
  {
    'GreenAddToCart':50,
    'YellowAddToCart':30,
    'ControlGroup':20
  },
  function(result) {
    if (result == 'GreenAddToCart') {
      $('.add-to-cart').css({
        'background-color':'green',
      });
    }else if (result == 'YellowAddToCar') {
      $('.add-to-cart').css({
        'background-color':'yellow',
      });
    }
  }
);
```

This code generates (randomly on client-side) an 50:30:20 A/B test on changing the add to cart button. Once your customer gets a variant of an A/B test, this value is stored in his cookie, so that next time he comes, he gets the same variant.

There is also an automatically tracked 'ab test' event, that contains the A/B test name and variant values, so that you can segment your customers based on this A/B test. This event is tracked only once.

<Callout icon="🚧" theme="warn">
  ### Important

  If the JS SDK is fully loaded and there is no callback function defined, the call returns a String with Variant name and you can process the response yourself. Use freely from Tags / Weblayers. Do not use without JS SDK fully loaded.
</Callout>

## showHtml()

You can create custom HTML blocks in Marketing campaign builder, which can be called up by this function. It lets you easily implement customized HTML elements into your webpage.

### Arguments

| Name                          | Value  | Description                                             |
| :---------------------------- | :----- | :------------------------------------------------------ |
| CSS selector **(Required)**   | String | CSS selector of item(s) which will hold your HTML block |
| HTML node name **(Required)** | String | Name of your HTML node                                  |

### Examples

```javascript
exponea.showHtml('div','myHtmlNode');
```

This call will asynchronously load content from Marketing backend that is associated under `myHtmlNode` for current customer and set it as `innerHTML` of all div elements on your page.

Scenario needs to run at least once before the content is available in `show/getHtml` response.

## getHtml()

You can even process your HTML block yourself by calling `getHtml` function, which returns the HTML block code.

### Arguments

| Name                             | Value    | Description                                          |
| :------------------------------- | :------- | :--------------------------------------------------- |
| HTML node name **(Required)**    | String   | Name of your HTML node                               |
| Callback function **(Required)** | Function | Callback function that processes the HTML block code |

### Examples

```javascript
exponea.getHtml(
  'myHtmlNode',
  function(html){
    // process the HTML block code in any way
  }
);
```

## getPageState()

Get the engagement signals the Web SDK has measured for the current page view — active time, scroll position, clicks, exit intent, and more. This is the same data [smart triggering](https://documentation.bloomreach.com/engagement/docs/smart-triggering-in-weblayers) uses to decide when a [weblayers](https://documentation.bloomreach.com/engagement/docs/web-layers) appears.

### Return value

| Property              | Value            | Description                                                                                         |
| :-------------------- | :--------------- | :-------------------------------------------------------------------------------------------------- |
| dwell\_time\_s        | Number           | Seconds since the page loaded, including idle time.                                                 |
| active\_time\_s       | Number           | Seconds the visitor spent actively interacting. Excludes idle periods and time in a background tab. |
| idle\_time\_s         | Number           | Seconds with no interaction.                                                                        |
| active\_ratio         | Number           | active\_time\_s divided by dwell\_time\_s, between 0 and 1.                                         |
| scroll\_position\_px  | Number           | Furthest scroll offset reached, in pixels. Only increases.                                          |
| page\_height\_px      | Number           | Total document height when you call the method.                                                     |
| viewport\_height\_px  | Number           | Value of window\.innerHeight when you call the method.                                              |
| page\_height\_changed | Boolean          | Whether the page grew by more than 20% since it loaded.                                             |
| sections\_visible     | Array of Strings | Selectors of the configured sections that have entered the viewport.                                |
| total\_clicks         | Number           | Number of clicks on the current page.                                                               |
| on\_mouse\_leave      | Boolean          | Whether the cursor left the page toward the browser's address bar or tabs. Desktop only.            |
| on\_return            | Boolean          | Whether the visitor returned after the tab was hidden.                                              |

All values reset when a new page loads.

### Examples

Read the current state and send it to your own analytics when the visitor leaves the page:

```javascript
window.addEventListener("pagehide", function () {
  const state = exponea.getPageState();
  myAnalytics.send("engagement", { activeSeconds: state.active_time_s, clicks: state.total_clicks });
});
```

<Callout icon="📘" theme="info">
  ### Note

  Call `exponea.getPageState()` with the legacy tracking snippet, or `brweb.getPageState()` with the unified Web SDK snippet.
</Callout>

## reloadWebLayers()

<Callout icon="📘" theme="info">
  This function is new in version `v2.2.0`.
</Callout>

Marketing handles loading of your weblayers automatically. However, in special cases (on SPA pages), you may need to control the re-loading of your weblayers by yourself. Function `reloadWebLayers` is used in such cases and it does:

1. Revert weblayers on the page.
2. Fetch and apply new weblayers from Marketing.
3. Call the user's callback after the weblayers are applied.

### Arguments

| Name     | Value    | Description                                                     |
| :------- | :------- | :-------------------------------------------------------------- |
| callback | Function | Execute custom function after successfully reloading weblayers. |

### Examples

Reload all weblayers and register a callback:

```javascript
const callback = () => console.log('Weblayers reloaded');
exponea.reloadWebLayers(callback);
```