---
schema_version: "1"
id: be5b6093d1af5f63c5f9ccc18ade546d5ce8bd3a6a6bab33292c2ceff18028d3
title: Context Events in Enhanced Web Chat v2
collection: developer
version: current
locale: en-us
portal_url: https://docs.salesforce.com/developer/current/en-us/service-cloud/messaging-web/guides/context-events.md
canonical_url: https://developer.salesforce.com/docs/service/messaging-web/guide/context-events.html
source_site: developer.salesforce.com
content_type: documentation
content_hash: 290966e66fa1d3ae9ca3a535dc8c371aebd49a3ea9ea24704883aae56b3dd2e6
products:
  - Enhanced Web Chat
  - Service Cloud Developer Content
---
# Context Events in Enhanced Web Chat v2

**important:** This method of passing context events is only available in Enhanced Web Chat v2. For more information, see [Enhanced Chat](https://help.salesforce.com/s/articleView?id=ai.agent_enhanced_chat_channel.htm) in Salesforce Help.

The optional utilAPI method enables you to pass information like the current page or a recent search to the agent. See the reference for [setSessionContext](/docs/service/messaging-web/references/m4w-reference/utilAPI.html#setsessioncontext).

**note:** Context events aren't processed for the agent welcome message. The agent processes context events with each user prompt. To pass information that the agent can use in the welcome message, use pre-chat variables instead. See [Create a Custom Pre-Chat Form Using LWC](/docs/service/messaging-web/guides/create-custom-pre-chat-form.html).

## Set Context Variables

The input parameter to `setSessionContext` is an array of context variables. Each context variable has a `name` and a typed `value`. The reserved variable `_AgentContext` holds page and search information under the `StructuredValue` type; custom context variables use their Agent Builder API name and can be any of the [supported types](#custom-context-variable-types).

```javascript
// Basic example with current page context
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "_AgentContext",
    value: {
      valueType: "StructuredValue",
      value: {
        currentPage: "https://example.com/products/laptops",
      },
    },
  },
]);

// Complete example with search context and event handlers
embeddedservice_bootstrap.utilAPI
  .setSessionContext([
    {
      name: "_AgentContext",
      value: {
        valueType: "StructuredValue",
        value: {
          currentPage: "https://example.com/search-results",
          search: {
            result: "MacBook Pro 16-inch",
            filters: ["Brand: Apple", "Price: $2000-$3000", "Memory: 16GB"],
            facets: ["Laptops", "Computers", "Electronics"],
          },
        },
      },
    },
  ])
  .then(() => {
    console.log("Successfully set context.");
  })
  .catch((error) => {
    console.log("Error setting context: " + error);
  });
```

**note:** Call `embeddedservice_bootstrap.utilAPI.setSessionContext` only after `onEmbeddedMessagingReady` fires; don't call it in `initEmbeddedMessaging`.

## Custom Context Variable Types

In addition to the `_AgentContext` structured object, you can pass any custom context variable that you've defined in Agentforce Builder. ECv2 supports all eight Agentforce Builder variable types. Each type maps to a specific `valueType` on the wire, with the value stored under a type-specific key.

| Agentforce Builder Type | `valueType`                     | Value Key                                 |
| :---------------------- | :------------------------------ | :---------------------------------------- |
| String                  | `TextValue`                     | `textValue`                               |
| Boolean                 | `BooleanValue`                  | `booleanValue`                            |
| Number                  | `IntegerValue` or `DoubleValue` | `integerValue` or `doubleValue`           |
| Currency                | `TextValue`                     | `textValue` (`"<CurrencyCode> <Amount>"`) |
| Date                    | `DateValue`                     | `dateValue` (`YYYY-MM-DD`)                |
| Timestamp               | `DateTimeValue`                 | `dateTimeValue` (ISO-8601)                |
| List                    | `ListValue`                     | `listValue` (array of typed values)       |
| Object                  | `StructuredValue`               | `value` (nested object)                   |

Each context variable's `name` must match its API name in Agentforce Builder, and **API write access** must be enabled for the variable.

**warning:** Non-conforming context variable payloads can be silently dropped by the server. See [Handle Rejected Context Variables](#handle-rejected-context-variables) for how to detect drops and the two rejection modes.

### String

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "OrderType",
    value: {
      valueType: "TextValue",
      textValue: "Shoes",
    },
  },
]);
```

### Boolean

Accepts the boolean literals `true` and `false`.

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "IsVIP",
    value: {
      valueType: "BooleanValue",
      booleanValue: true,
    },
  },
]);
```

### Number

Use `IntegerValue` for whole numbers and `DoubleValue` for decimals. The numeric value must be a JSON number, not a string.

```javascript
// Integer
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "OpenCases",
    value: {
      valueType: "IntegerValue",
      integerValue: 7,
    },
  },
]);

// Double
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "AverageOrderValue",
    value: {
      valueType: "DoubleValue",
      doubleValue: 1499.99,
    },
  },
]);
```

### Currency

Currency values use `TextValue` with a string in the format `"<CurrencyCode> <Amount>"`, for example `"USD 1499.99"`. Sending a bare number, an amount without a currency code, or an amount with a currency symbol causes the server to drop the variable.

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "OrderTotal",
    value: {
      valueType: "TextValue",
      textValue: "USD 1499.99",
    },
  },
]);
```

### Date

Date-only value in `YYYY-MM-DD` format.

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "RenewalDate",
    value: {
      valueType: "DateValue",
      dateValue: "2026-08-15",
    },
  },
]);
```

### Timestamp

ISO-8601 date and time. Both `YYYY-MM-DDTHH:MM:SS` and `YYYY-MM-DDTHH:MM:SSZ` are accepted.

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "LastLogin",
    value: {
      valueType: "DateTimeValue",
      dateTimeValue: "2026-05-22T14:30:00Z",
    },
  },
]);
```

### List

`ListValue` wraps an array of typed values under `listValue`. Each item is itself a value with its own `valueType`, and all items must share the same `valueType` — the type must also match what's configured for the variable in Agentforce Builder.

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "search_facets",
    value: {
      valueType: "ListValue",
      listValue: [
        { valueType: "TextValue", textValue: "billing" },
        { valueType: "TextValue", textValue: "refund" },
      ],
    },
  },
]);
```

### Object

Object variables use the `StructuredValue` shape with an arbitrary nested object under `value`. This is the same shape used by the reserved `_AgentContext` variable shown in [Set Context Variables](#set-context-variables).

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext([
  {
    name: "ObjectVar",
    value: {
      valueType: "StructuredValue",
      value: {
        prop1: "TestPage",
        prop2: {
          prop2_1: "Branded Shoes",
          prop2_2: ["Red Shoes"],
          prop2_3: ["Expensive"],
        },
      },
    },
  },
]);
```

### Handle Rejected Context Variables

The server validates each context variable payload against its declared `valueType`. There are two rejection modes.

| Rejection Mode | Trigger                                                                                                                                                     | Client Behavior                                                                                                                                                                               |
| :------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Hard rejection | Schema violation. For example, a `valueType` of `IntegerValue` with a string in `integerValue`, or an unquoted string literal in `textValue`.               | The entire request is rejected.                                                                                                                                                               |
| Soft rejection | Type or format mismatch. For example, a Currency variable sent as `DoubleValue`, a `DateValue` in the wrong format, or a `ListValue` with mixed item types. | The individual variable is silently dropped. The request otherwise proceeds. Dropped variable names are listed in a warning message in the next send-message or create-conversation response. |

**warning:** `setSessionContext` resolves successfully even when a variable is soft-rejected — the promise resolution only indicates that the call was queued on the client. To confirm that a variable was accepted by the server, inspect the response to the next send-message or create-conversation call for a warning naming the dropped variable.

<!--
CONFIRM WITH ENG (Nishant / Sachin):
- Exact field name(s) on the send-message and create-conversation response that carry
  the soft-rejection warnings (e.g., `warnings[]`, `droppedVariables[]`, `messageWarnings`).
- Sample response payload with a soft-rejection warning attached, so developers know what to
  look for in the callback.
- Whether the warning surface differs between the send-message response and the
  create-conversation response.
Once confirmed, add a "Response format" subsection here with the field name and a sample.
-->

By default, context variables set through `setSessionContext` are held on the client and included with the next end-user message. To pass context variables when a new conversation is created — before the end user sends their first message — pass an `options` object as the second argument with `sendWithNewConversation` set to `true`.

| Field Name                | Type    | Description                                                                                                                                                                    |
| :------------------------ | :------ | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sendWithNewConversation` | Boolean | Optional. Defaults to `false`. When `true`, the context variables are sent as part of creating a new conversation instead of being deferred to the next end-user message turn. |

```javascript
embeddedservice_bootstrap.utilAPI.setSessionContext(
  [
    {
      name: "AccountName",
      value: {
        valueType: "TextValue",
        textValue: "Acme Corporation",
      },
    },
  ],
  { sendWithNewConversation: true },
);
```

## Set Context Variables and Send a Message

You can set context variables and send a user utterance in a single call with `sendTextMessage`. Setting variables and sending a message in a single call makes sure that the context is immediately available for the agent.

```javascript
embeddedservice_bootstrap.utilAPI
  .sendTextMessage("I need help with this product", [
    {
      name: "_AgentContext",
      value: {
        valueType: "StructuredValue",
        value: {
          currentPage: "https://example.com/products/laptops",
          search: {
            result: "MacBook Pro 16-inch",
            filters: ["Brand: Apple", "Price: $2000-$3000"],
            facets: ["Laptops", "Computers", "Electronics"],
          },
        },
      },
    },
  ])
  .then(() => {
    console.log("Successfully sent message with context.");
  })
  .catch((error) => {
    console.log("Error sending message with context: " + error);
  });
```

## Create Context Variables in Agentforce Builder

Before you can access context variables in new agents, manually create them in Agentforce Builder. See [Create Variables In Agentforce Builder](https://help.salesforce.com/s/articleView?id=ai.agent_builder_variables_create.htm&type=5).

For the `currentPage` and `search` variables supported by ECv2, create four variables with these settings.

**note:** Enable **API write access** for each variable.

| Name             | API Name         | Data Type | List Item Type |
| ---------------- | ---------------- | --------- | -------------- |
| `currentPage`    | `currentPage`    | String    | N/A            |
| `search_result`  | `search_result`  | String    | N/A            |
| `search_filters` | `search_filters` | List      | String         |
| `search_facets`  | `search_facets`  | List      | String         |

### Access Context Variables

You can access the context variables in Agent Script using `${!@variables.<apiName>}`. For example, use `{!@variables.currentPage}` to reference the current page in an action input. For more information on agent variables, see [Agent Script Reference: Variables](https://developer.salesforce.com/docs/ai/agentforce/guide/ascript-ref-variables.html).

## Event Handlers

You can use event handlers in both `setSessionContext()` and `sendTextMessage()` methods to perform actions after the operation completes.

- `then` event handler— If the context is set successfully, you can use this handler to, for example, update the UI or record analytics.
- `catch` event handler— If there's an error setting the context, you can use this handler to, for example, try again or show an error message.
- `finally` event handler— This handler runs after the attempt to set context completes, whether it succeeds or fails. Use this handler to run any clean-up actions.
