JavaScript Integration

JavaScript SDK will let you integrate with React, Meteor, AngularJS and more. Enter to see how to use widget methods, enable events etc.
Dashboard mockup

JavaScript Widget Integration

The User.com JavaScript SDK allows you to interact and exchange data with the User.com application directly from your website’s frontend. Using the global UE object, the userengage function, and the window.civchat configuration, you can initialize the chat widget, manage user and company data, send custom events, track navigation, and control widget behavior.

You can use this SDK to:

  • Track users and page views using UE.pageHit()
  • Initialize user sessions with attributes passed via window.civchat
  • Respond to widget lifecycle events using callback functions
  • Send events, update user data, or manage widget state dynamically with userengage

This guide covers JavaScript integration only.For backend/server-side usage, refer to the REST API documentation. For mobile apps, refer to the Mobile SDK documentation.

Basic Widget Initialization

To begin tracking anonymous users and enabling widget functionalities, include the following script before the closing <body> tag of your page:

Copied to clipboard!
<script data-cfasync="false" type="text/javascript">
  window.civchat = {
    apiKey: "YOUR_API_KEY"
  };
</script>
<script data-cfasync="false" type="text/javascript" src="https://YOUR_SUBDOMAIN.user.com/widget.js"></script>
  

This setup initializes the widget. Users will be tracked anonymously since no user attributes are included.

After the script loads, you gain access to the userengage namespace and UE methods.

Passing User Attributes

You can pass user (and company) attributes by extending the window.civchat object. Example:

Copied to clipboard!
window.civchat = {
    apiKey: "YOUR_API_KEY",
    name: "John Doe",
    user_id: "52bdc3be5145e87076c8",
    email: "johndoe@example.com",
    gender: 2,
    status: 2,
    date_attr: "2017-07-25T14:14:08.612Z",
    phone_number: "+44754123434",
    score: 0,
    company: {
        name: "My Company",
        company_id: "12345",
        revenue: "$239.9 billion"
    }
};
Note: These values can be dynamically set using GTM variables or JavaScript.

If a user_id is included:

  • If a user with that ID exists: tracking switches to that user.
  • If not: the ID is assigned to the currently tracked user, effectively updating their record without creating a duplicate.

Formatting for Custom Attributes

  • Fixed type: { fixed_attr: "value" } or { fixed_attr: ["value"] }
  • Fixed type (multi-choice): { fixed_attr: ["value1", "value2"] }
  • DateTime (ISO 8601): { datetime_attr: "2016-08-03T12:00:00+00:00" }
  • Date (YYYY-MM-DD): { date_attr: "2016-08-03" }

Widget State Options

You can control how the chat widget appears on page load by specifying a state value inside the window.civchat object:

Copied to clipboard!
window.civchat = {
    apiKey: "YOUR_API_KEY",
    state: "standard"
};

Supported state values:

  • "simple" – displays only the widget icon
  • "standard" – displays the widget icon with a greeting message
  • "hidden" – completely hides the widget
This setting overrides the default state configured under Settings → Chat Widget Settings in the User.com app. Use it when you need programmatic control over the widget's visibility or behavior on specific pages.

Widget Callbacks

onLoad

Triggered after the widget loads.

Copied to clipboard!
onLoad: function() {
    console.log('Widget loaded');
    dataLayer.push({ event: "User.com - Widget Ready" }); //Optional: trigger Data Layer event
    window.userComReady = true; //Optional: set a global variable
    dispatchEvent(new Event('userComReady')); //Optional: dispatch JS event 
}

onPayloadReceived

Handles messages from the automation Send Code module.

Copied to clipboard!
onPayloadReceived: function (message) {
    console.log('Payload received:', message);
    if (typeof message === "string") {
        try {
            var fn = new Function(message);
            fn();
        } catch (e) {
            console.error("UE - error executing message as function:", e);
        }
    }
}

onMessage

The onMessage callback is triggered for every incoming chat message. The message object passed to this function contains details about the message, including its content and origin.

The isAdmin property within the message object indicates the source of the message:

  • If isAdmin is set to true, the message originated from the backend side (e.g., an agent or automation).
  • If isAdmin is false, the message was sent from the front-end widget by the user.

This distinction allows you to handle messages differently based on their origin.

Copied to clipboard!
onMessage: function (message) {
    console.log('Received message from widget:', message);
    console.log('Message type:', typeof message);
    console.log('Message content:', JSON.stringify(message, null, 2));
    if (message.isAdmin) {
        // Handle backend-originated message
    } else {
        // Handle user-originated message
    }
}

Sample message object:

Copied to clipboard!
{
    "content": "Hello, user!",
    "isAdmin": true
};

In this example, since isAdmin is true, the message was sent from the backend side.

onOpen

Triggered when the widget is opened (expanded by the user or programmatically).

Copied to clipboard!
onOpen: function () {
    console.log("Widget opened");
    // Custom logic here
}

onClose

Triggered when the widget is closed by the user or programmatically.

Copied to clipboard!
onClose: function () {
    console.log("Widget closed");
    // Custom logic here
}

Widget callbacks - example usage

Copied to clipboard!
window.civchat = {
        apiKey: "YOUR_API_KEY",
        name: "John Doe",
        user_id: "52bdc3be5145e87076c8",
        email: "johndoe@example.com",
        phone_number: "+48123456789",
        //Optional: trigger Data Layer event
        onLoad: function () {
            dataLayer.push({ event: "User.com - Widget Ready" });
        },
        //Optional: action on message
        onMessage: function (message) {
            console.log('Received message from widget:', message);
            console.log('Message type:', typeof message);
            console.log('Message content:', JSON.stringify(message, null, 2));
            if (message.isAdmin) {
                // Handle backend-originated message
            } else {
                // Handle user-originated message
            }
        },
        //Optional: handle Send Code message
        onPayloadReceived: function (message) {
            console.log('Payload received:', message);
            if (typeof message === "string") {
                try {
                    var fn = new Function(message);
                    fn();
                } catch (e) {
                    console.error("UE - error executing message as function:", e);
                }
            }
        },
        onOpen: function () {
            console.log("Widget opened");
            // Custom logic here, e.g., logging or analytics
        },
        onClose: function () {
            console.log("Widget closed");
            // Custom logic here, e.g., logging or analytics
        }
    };

Widget methods

UE.pageHit()

The UE.pageHit() method sends a virtual page view to our servers, simulating navigation on single-page applications (SPAs). This method updates the user's session with any attributes passed and records a page view based on the current browser URL (retrieved automatically—no need to include it manually in the payload).

Calling UE.pageHit() will:

  • Record a new page view for the current user, using the current window.location.href as the URL
  • Update the user profile with any included user or company attributes
  • Optionally trigger an event via the event object passed in the call
Copied to clipboard!
UE.pageHit({
    name: "John Doe",
    email: "myemail@example.org",
    ... // other attributes
});

You can also send custom events:

Copied to clipboard!
UE.pageHit({
    name: "John Doe",
    email: "myemail@example.org",
    event: {
        event_name: "Custom event",
        custom_attribute: "value"
    }
});

With unified identification enabled UE.pageHit has ability to switch tracking in browser to the different user. In such case it may be important to send event together with UE.pageHit and not by a separate userengage function call. You can read more about it here.

UE.resetAuth()

The UE.resetAuth() method resets the __ca__chat cookie and global tracking context. It immediately ends the current user's session and starts tracking a new user. This function is commonly used when a user logs out of your application, as it ensures the next visitor session begins anonymously or with a fresh identity.

Calling this method will:

  • Remove the existing tracking cookie
  • Generate a new tracking session
  • Prevent the previous user from accessing chat history

You must include the apiKey in the payload every time you use this method.

Copied to clipboard!
UE.resetAuth({ 
    apiKey: "YOUR_API_KEY" 
});

You can also pass new user details:

Copied to clipboard!
UE.resetAuth({
    apiKey: "YOUR_API_KEY",
    email: "newuser@example.com"
});

Behavior with "Authorize by email" option

When Authorize by email is enabled (must be activated by our support), UE.resetAuth() will check if a user with the provided email already exists:

  • If the user exists → tracking switches to that user.
  • If not → a new user is created.

When Authorize by email is disabled (default):

  • A new user is always created with the provided email, even if a user with that email already exists.

To learn more about these scenarios and how they relate to tracking behavior, refer to the Unified Identification section below.

UE.destroy()

Removes the widget instance from the DOM. After the current widget instance has been destroyed, you cannot refer to the UE methods. This method takes no arguments.

Copied to clipboard!
UE.destroy();

Additional userengage Methods

The userengage function provides a versatile interface to interact with the User.com platform, allowing you to send custom events, product-related events, update user attributes, and control the chat widget's state.

Sending Custom Events

You can track user interactions by sending custom events along with associated attributes:

Copied to clipboard!
userengage("event.name", {
    event_attr1: "value1",
    event_attr2: "value2"
});

Note: It's not required to predefine events or their attributes before sending them. However, if you send attributes without defining them in advance, they will be automatically created with a String data type. Additionally, attributes are optional when sending events. To maintain clean and accurate data structure, it's recommended to predefine attributes with the correct data types in your User.com app. You can read more about events here.

Product Events

To monitor user interactions with products, such as adding items to a cart you can use product events:

Copied to clipboard!
userengage("product_event", {
    product_id: "12345",
    event_type: "add to cart",
    name: "Product Name",
    description: "Product description"
});

Required fields: product_id and event_type.

Optional fields: name, description, and any other relevant product attributes.

Event types include: add to cart, purchase, liking, add to observation, order, reservation, return, view, click, detail, add, remove, checkout, checkout option, refund, promo click.

Important: Product attribute are updated with the latest values sent. This means historical values aren't stored, and each new event updates the product's profile with the latest information.

To learn more about product events, click here.

Updating User Attributes

To update user attributes without triggering a page view, use the client.update method:

Copied to clipboard!
userengage("client.update", {
    attribute: "value"
});

Note: Not all attributes can be updated using this method. Ensure the attributes you intend to update are permitted. You can learn more about it here.

Managing Widget State

Control the chat widget's visibility and state using the following command:

Copied to clipboard!
userengage("widget.{{state}}");

These methods allow for dynamic control over the chat widget's behavior based on user interactions or specific conditions on your website. You can set up one of the following states:

State
Description
hide
Change widget state to hidden
open
Change widget state to expanded
show
Change widget state to standard
close
Closes opened chat window

Unified Identification

Unified Identification in ensures consistent user tracking by linking sessions across devices and cookies using email, user_id, and widget session data. This feature affects both UE.pageHit() and UE.resetAuth() methods and must be enabled by User.com support.

The primary goal is to prevent duplicate users from being created based on email, ensuring accurate identification and continuity across user sessions. By default, Unified Identification is disabled—so passing an email in pageHit() will overwrite the current user's email without checking if the same email is already assigned to another user, and resetAuth() will always create a new user.

When Unified Identification is enabled, the platform intelligently manages identity using cookie state and user attributes. It works in tandem with an additional setting—Authorize by email, which is also activated by User.com support. Importantly, these mechanisms apply only when an email is passed and no user_id is included in the request.

The behavior differs based on the state of Authorize by email:

  • With Authorize by email enabled:
    • In pageHit():
      • If the provided email matches the cookie's current user, the session continues normally.
      • If the email differs:
        • If a user with that email exists: tracking switches to that user.
        • If not: a new user is created and tracking switches to that user.
    • In resetAuth():
      • If a user with the provided email exists: tracking switches to that user.
      • If not: a new user is created and tracking switches to that user.
  • With Authorize by email disabled:
    • In pageHit():
      • If the current user already has an email, it won’t be overwritten - new user will be created and tracking switched.
      • If the current user has no email: the provided one is assigned.
      • The system will not check for existing users with the same email.
    • In resetAuth():
      • A new user is always created with the provided email, regardless of whether it exists in the app or is already tracked.

In both methods, if a match occurs (cookie/email), user attributes can be updated and events triggered as expected. To ensure reliable identity handling and prevent email duplication, it is strongly recommended to enable both Unified Identification and Authorize by email.

To request activation of these features, please contact our support through the chat.

Haga crecer su negocio de forma automática

No pierdas el tiempo en tareas repetitivas. Deja que las automatizaciones se encarguen de ello.
¡Gracias! ¡Su presentación ha sido recibida!
¡Uy! Algo salió mal al enviar el formulario.