NAV
javascript
  • JavaScript API
  • JavaScript API

    The JavaScript API offers many different methods which you can use to customize the live chat look and functionality for your visitors. These methods may be used inside the SnapEngage code snippet where it says /* Place your SnapEngage JS API code below */ which will cause the API method to run after the SnapEngage code is fully loaded. In some cases, some API methods may be used as an event handler on an element on the page. For example, you can set a link's onclick attribute to SnapEngage.startLink() which will open up the chat if someone clicks that link.

    Authentication for JavaScript API

    An authentication key is not needed to use the Javascript API.

    Just be sure to place your function calls inside your SnapEngage code snippet where it says "Place your SnapEngage JS API code below"

    API Placement and Availability

    Since the SnapEngage code snippet loads asynchronously, there are certain limitations on when you can use, and/or have access to our Javascript API.

    Unlike a non-asynchronous include, you cannot be sure that the SnapEngage functions will be available when the document is otherwise ready.

    Use our API inside the SnapEngage JavaScript Code Snippet

    <!-- begin SnapEngage code -->
    <script type="text/javascript">
      (function() {
        var se = document.createElement('script'); se.type = 'text/javascript'; se.async = true;
        se.src = '//storage.googleapis.com/code.snapengage.com/js/...';
        var done = false;
        se.onload = se.onreadystatechange = function() {
          if (!done&&(!this.readyState||this.readyState==='loaded'||this.readyState==='complete')) {
            done = true;
            /* Place your SnapEngage JS API code below */
            /* Example JS API: Enable sounds for Visitors. */
            var allow = true;
            SnapEngage.allowChatSound(allow);
          }
        };
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(se, s);
      })();
    </script>
    <!-- end SnapEngage code -->
    

    This code snippet has a built in safety net, so to speak, for our Javascript API availability. As long as you place all of your custom Javascript API inside this code block, you can be sure that SnapEngage functions will be available. Be sure to place your function calls after the comment /* Place your SnapEngage JS API code below */.

    We recommend that you call API exclusively inside this block. But if you insist on going all cowboy on us...

    Using it elsewhere can be tricky

    Our chat code is well optimized and loads quickly, but we also defer to your local page first (by design). So if you have a hang or a snag or even just a slow-loading image on your page, it might mean a slight additional delay to the SnapEngage code’s availability.

    So what are you to do if you want, say, a hard-coded link on your page that fires onclick="SnapEngage.startLink();" but you want to make sure that function exists before a Visitor clicks it?

    One option would be hiding the element until SnapEngage finishes loading, then reveal the element. This is relatively painless to achieve with jQuery or something like it, and only slightly less painless with vanilla Javascript.

    JavaScript Events

    At some point, you may need to hook your custom code into JavaScript events, or you may want to instruct Google Analytics to track certain events. In this article you will find all of SnapEngage's JavaScript Events, and a few example uses.

    Close Event

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('type: ' + type);
        console.log('status: ' + status);
    });
    

    The Close event is fired when a close button is clicked.

    This callback can return two pieces of info: type of window that was closed, and widget status when the close event was fired.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: type and status. Inside the anonymous function, you can check the returned value of the type and status parameters.
    type String The type of window that was closed (see table of values below).
    status String The widget status when the close event was fired (see table of values below).

    Return values of type parameter

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('A visitor just closed the ' + type + ' window.');
    });
    
    // The callback above returns this
    // when the visitor closes a chat window
    'A visitor just closed the chat window.'
    
    Type Value Description
    String 'form' The visitor closed a prechat or offline form.
    String 'chat' The visitor closed a chat window.
    String 'proactive' The visitor closed a proactive chat window.

    Return values of status parameter

    SnapEngage.setCallback('Close', function (type, status) {
        console.log('A visitor closed a ' + type +
         ' and the widget is ' + status + '.');
    })
    
    // The callback above returns this
    // when the visitor closes a form
    'A visitor closed a form and the widget is offline.'
    
    Type Value Description
    String 'online' The visitor closed a window when the widget was online.
    String 'offline' The visitor closed a window when the widget
    was offline.

    ChatMessageReceived Event

    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
        console.log('agent: ' + agent);
        console.log('msg: ' + msg);
    });
    

    The ChatMessageReceived event is fired when a message from the agent is received by the visitor.

    This callback can return two pieces of info: name of the agent that sent the message, and the msg that was sent.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: agent and message. Inside the anonymous function, you can check the returned value of the agent and message parameters.
    agent String The agent alias.
    msg String The message that was received by the visitor.

    Return values

    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
        console.log('A visitor received a chat message from ' + agent);
        console.log('And the msg was: ' + msg);
    });
    
    // The callback above returns this
    // when the visitor receives a chat message
    'A visitor received a chat message from Samantha';
    'And the msg was: hello ';
    

    Example return values of agent and msg are inside the code example.

    ChatMessageSent Event

    SnapEngage.setCallback('ChatMessageSent', function (msg) {
        console.log('msg: ' + msg);
    });
    

    The ChatMessageSent event is fired when the visitor submits a chat message while in the chat session.

    This callback can return one piece of info: the msg that was sent by the visitor.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: msg. Inside the anonymous function, you can check the returned value of the msg parameter.
    msg String The message that was sent by the visitor.

    Return values

    SnapEngage.setCallback('ChatMessageSent', function (msg) {
        console.log('A visitor sent this chat message: ' + msg);
    });
    
    // The callback above returns this
    // when a visitor sends a chat message
    'A visitor sent this chat message: What does SnapEngage integrate with?';
    

    An example return value of msg is inside the code example.

    MessageSubmit Event

    SnapEngage.setCallback('MessageSubmit', function (email, msg) {
        console.log('email: ' + email);
        console.log('msg: ' + msg);
    });
    

    The MessageSubmit event is fired when the visitor submits an offline message (not a chat message).

    This callback can return two pieces of info: the visitor's email, and the msg that was sent.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: email and msg. Inside the anonymous function, you can check the returned value of the email and msg parameters.
    email String The visitor's email address.
    msg String The message.

    Return values

    SnapEngage.setCallback('MessageSubmit', function (email, msg) {
        console.log(email + ' just submitted an offline message.');
        console.log('The message was: ' + msg);
    });
    
    // The callback above returns this
    // when an offline message is submitted
    '[email protected] just submitted an offline message.'
    'The message was: hello!';
    

    Example return values of email and msg are inside the code example.

    Minimize Event

    NOTE: This API is only available for Design Studio widgets. Please consider upgrading to get the most current functionality.

    SnapEngage.setCallback('Minimize', function(isMinimized, chatType, boxType) {
        // Handle results.
        console.log('Chatbox is' + (isMinimized ? '' : ' not') + ' minimized');
        console.log('Chat Type is: ' + chatType);
        console.log('Chat Box is: ' + boxType);
    });
    

    The Minimize event is triggered when the visitor clicks the minimize icon in the chat box, or during live and active chats when they click on the minimized 'button' to maximize the chat box.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts three optional parameters: isMinimized, chatType and boxType. Inside the anonymous function, you can handle the returned values of isMinimized, chatType and boxType arguments.
    isMinimized Boolean The state of the chat box AFTER the visitor has clicked.
    chatType String The type of chat the visitor is using.
    boxType String The type of the chat box the visitor sees.

    Return values of isMinimized parameter

    SnapEngage.setCallback('Minimize', function(isMinimized, chatType, boxType) {
        // Handle results.
        console.log('Chatbox is' + (isMinimized ? '' : ' not') + ' minimized');
        console.log('Chat Type is: ' + chatType);
        console.log('Chat Box is: ' + boxType);
    });
    
    // The callback above returns this
    // when a visitor has minimized a manual live chat:
    'Chatbox is minimized'
    'Chat Type is manual'
    'Chat Box is chatManual'
    
    Type Value Description
    Boolean true The chat box is minimized.
    Boolean false The chat box is not minimized (maximized).

    Return values of chatType parameter

    Type Value Description
    String 'manual' The visitor started a manual chat.
    String 'proactive' The visitor started a proactive chat.

    Return values of boxType parameter

    Type Value Description
    String 'chatManual' The box is an ongoing live chat box initiated by the vistitor.
    String 'intelliPrechat' The box is a Intelligent Prechat form
    String 'offline' The box is an Offline form
    String 'prechat' The box is a Prechat form
    String 'proactive' The box is an ongoing live chat box initiated by the proactive rules.
    String 'proactiveInvite' The box is displaying the proactive invite, awaiting response by the visitor

    Open Event

    SnapEngage.setCallback('Open', function (status) {
        console.log('status: ' + status);
    });
    

    The Open event is fired when the chat form is opened. The form may be opened by the user directly (button click), or as the result of an API call.

    This callback can return one piece of info: the widget status when the event was fired.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts an optional parameter: status. Inside the anonymous function, you can check the returned value of the status parameters.
    status String The widget status at the time the event was fired.

    Return values of status parameter

    SnapEngage.setCallback('Open', function (status) {
        console.log('A form just opened and the widget status is: ' + status);
    });
    
    // The callback above returns this
    // when a form is opened and the widget is offline
    'A form just opened and the widget status is: offline'
    
    Type Value Description
    String 'online' The widget is online.
    String 'offline' The widget is offline.

    OpenProactive Event

    SnapEngage.setCallback('OpenProactive', function (agent, msg) {
        console.log('agent: ' + agent);
        console.log('msg: ' + msg);
    });
    

    The OpenProactive event is fired when the proactive chat is displayed to a visitor. (Note, when the visitor replies, the StartChat event fires.)

    This callback can return two pieces of info: the name of the agent used in the proactive message, and the proactive msg itself.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts two optional parameters: agent and msg. Inside the anonymous function, you can check the returned value of the agent and msg parameters.
    agent String The agent alias.
    msg String The proactive prompt message.

    Return values

    SnapEngage.setCallback('OpenProactive', function (agent, msg) {
        console.log('A proactive message just popped up. The agent shown is ' +
         agent + '.');
        console.log('The proactive message used is: ' + msg);
    });
    
    // The callback above returns this
    // when a proactive prompt opens
    'A proactive message just popped up. The agent shown is Samantha.';
    'The proactive message used is: You know nothing, Jon Snow.';
    

    Example return values of agent and msg are inside the code example.

    StartChat Event

    SnapEngage.setCallback('StartChat', function (email, msg, type) {
        console.log('email: ' + email);
        console.log('msg: ' + msg);
        console.log('type: ' + type);
    });
    

    The StartChat event is fired when the visitor starts a chat, or responds to a proactive invitation.

    This callback can return three pieces of info: the visitor's email, the visitor's first msg, and the type of chat (manual or proactive).

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts three optional parameters: email, msg, and type. Inside the anonymous function, you can check the returned value of the email, msg, and type parameters.
    email String The visitor's email address.
    msg String The visitor's first message.
    type String The type of chat.

    Return values

    SnapEngage.setCallback('StartChat', function (email, msg, type) {
        console.log(email + ' just started a ' + type + ' chat.');
        console.log('The message was: ' + msg);
    
    });
    
    // The callback above returns this
    // when the visitor starts a manual chat
    '[email protected] just started a manual chat.';
    'The message was: The King in the North!';
    

    Example return values of email, msg, and type are inside the code example.

    Return values of type parameter

    Type Value Description
    String 'manual' The visitor started a manual chat.
    String 'proactive' The visitor started a proactive chat.

    StartCallme Event

    SnapEngage.setCallback('StartCallme', function (phone) {
        console.log('phone: ' + phone);
    });
    

    The StartCallMe event is fired when the visitor starts a call-me.

    This callback can return one piece of info: the visitor's phone number.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: phone. Inside the anonymous function, you can check the returned value of the phone parameters.
    phone String The visitor's phone number.

    Return values

    SnapEngage.setCallback('StartCallMe', function (phone) {
        console.log('A visitor just started a callme request.');
        console.log('Their phone number is ' + phone);
    });
    
    // The callback above returns this
    // when the visitor starts a callme request
    'A visitor just started a callme request.'
    'Their phone number is 555-1234';
    

    Example return values of phone are inside the code example.

    SwitchWidget Event

    NOTE: This API is only available for Design Studio widgets. Please consider upgrading to get the most current functionality.

    SnapEngage.setCallback('SwitchWidget', function(newWidgetId) {
        // Handle results.
        console.log('I just switched to widget ID: ' + newWidgetId);
    });
    

    You must have the widget selector enabled in your Design Studio prechat &/or offline form to utilize this event callback functionality. The switchWidget event is triggered when the visitor has selected a value from the available dropdown list options. It will return the value of the newWidgetId.

    Parameter values

    Parameter Type Description
    Anonymous Function Function This callback function accepts one optional parameter: newWidgetId. Inside the anonymous function, you can handle the returned value of the newWidgetId argument.
    newWidgetId String The widgetId of the selected option.

    Return values of newWidgetId parameter

    SnapEngage.setCallback('SwitchWidget', function(newWidgetId) {
        // Handle results.
        console.log('I just switched to widget ID: ' + newWidgetId);
    });
    
    // The callback above returns this
    // when a visitor has selected an option:
    'I just switched to widget ID: 123-abc'
    

    Button Event

    The InlineButtonClicked event is fired when the visitor clicks on messages that are buttons.

    SnapEngage.setCallback('InlineButtonClicked', function(options) {
        console.log('A visitor clicked on a bot button sent from ' + options.botName);
        console.log('And the button label was: ' + options.buttonLabel);
        console.log('And the button value was: ' + options.buttonValue);
    });
    

    Parameter values

    Parameter Type Description
    options object Object containing information about the button that got clicked

    Options object

    Property name Type Description
    botName string Bot name (alias) that sent button message
    buttonLabel string Label of the button
    buttonValue string Value of the button

    ChatEnded Event

    The ChatEnded event fires when the chat ends. If your widget has chat survey enabled or any other post chat feature, this event is fired at the same time the post chat flow starts.

    SnapEngage.setCallback(SnapEngage.callbacks.CHAT_ENDED, function(options) {
        console.log('Who has ended the chat?');
        console.log(options.endedByUser ? "Visitor" : "Agent or the System");
    });
    

    Parameter values

    Parameter Type Description
    options object An object containing options

    Options object

    Property Type Description
    endedByUser boolean Whether the user has ended the chat or not

    Rating Prompt Clicked Event

    SnapEngage.setCallback('RatingPromptClicked', function (botAlias, scaleType, selectedOption) {
        console.log('botAlias: ' + botAlias);
        console.log('scaleType: ' + scaleType);
        console.log('selectedOption: ' + selectedOption);
    });
    

    The RatingPromptClicked event is fired when the rating prompt is clicked on the visitor side.

    This callback can return three pieces of info: botAlias of agent the visitor is interacting with, the scaleType of the rating, and the selectedOption as a number.

    Parameter values

    Parameter Type Description
    Function Function This callback function accepts two optional parameters: botAlias, scaleType, and selectedOption. Inside the anonymous function, you can check the returned value of the botAlias, scaleType, and selectedOption parameters.
    botAlias String The agent alias the visitor is interacting with.
    scaleType String The scale type, NUMBER or STAR.
    selectedOption Number The rate selected by the visitor.

    API Methods

    .allowChatSound()

    var allow = true;
    SnapEngage.allowChatSound(allow);
    

    Enable or disable all sounds produced by SnapEngage for chat visitors.

    Parameters

    Parameter Type Description
    allow boolean If set to true, chat sounds will play for the visitor e.g. when the a message is received. If set to false, chat sounds will not play.

    .allowPageChangeNotification()

    var allow = true;
    SnapEngage.allowPageChangeNotification(allow);
    

    Deprecated. We are not supporting this API at present. Instead, please use this setting inside your Admin Dashboard as described here.

    Should the Chat notify the agent when the visitor navigates to a new page? The notification will include a url to the page in question.

    Parameters

    Parameter Type Description
    allow boolean If set to true, your agent will be notified of page changes. This feature is enabled by default, but can be turned off by calling this method with the value false.

    .allowProactiveChat()

    var allow = true;
    SnapEngage.allowProactiveChat(allow);
    

    Should proactive chat invitations be allowed to fire? You can use this to disable (or re-enable) proactive chat wherever it might be necessary.

    This option can also be easily configured in the Admin Dashboard. The API call exists primarily for special circumstances, where you want to enable or disable use of proactive chat on specific pages.

    Parameters

    Parameter Type Description
    allow boolean If set to true, proactive chat invitations are enabled. If set to false, there will be no proactive chat invitations.

    .allowScreenshot()

    var allow = true;
    SnapEngage.allowScreenshot(allow);
    

    Deprecated. We are not supporting the screenshot option at present.

    Should the Pre-Chat and Offline forms include the Screenshot option? (The screenshot lets visitors send a screenshot of the current page to the agent.)

    Parameters

    Parameter Type Description
    allow boolean If set to true, legacy prechat and offline forms will include an option for visitors to send a screenshot. If set to false, the forms will not include the screenshot option.

    .clearAllCookies()

    SnapEngage.clearAllCookies();
    

    Clear and delete all cookies set by SnapEngage for the current visitor.

    No Parameters

    .disableLightbox()

    DEPRECATEDThis API has been deprecated as of Oct 8th, 2019.

    SnapEngage.disableLighbox();
    

    Disable the "Lightbox" effect for the prechat form. That is: the greyed-out background when the prechat form comes up.

    No Parameters

    .getAgentStatusAsync()

    SnapEngage.getAgentStatusAsync(function (online) {
        if (online) {
            console.log('chat is online/available');
        } else {
            console.log('chat is offline');
        }
    });
    

    Check whether or not you have agents online and your live chat is available.

    Parameters

    Parameter Type Description
    Anonymous Function Function This callback function uses a required parameter "online" which is a boolean. Inside the function, you can check the value of the "online" parameter, which will evaluate to true if agents are online and chat is available, or false if no agents are online and/or chat is not available.

    Common reasons for chat being unavailable include: All agents are paused, or it is outside of the widget's configured "Hours of Operation".

    Example getAgentStatusAsync() Usage

    Hide the chat button if chat is unavailable
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            SnapEngage.hideButton();
        }
    });
    

    Hide the SnapEngage button when your agents are offline/unavailable.

    Hide a custom inline button if chat is unavailable
    // Using Javascript
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            document.getElementById('myInlineButtonId').style.display = 'none';
        }
    });
    
    // Using jQuery
    SnapEngage.getAgentStatusAsync(function (online) {
        if (!online) {
            $('#myInlineButtonId').hide();
        }
    });
    

    If you have a custom button image that you've embedded into your site, you may want to show or hide it if the widget is online or offline. This is how you would do that.

    Check agent status every three minutes
    var threeMinutes = 3 * 60 * 1000;
    var tid = setTimeout(checkChatStatus, threeMinutes);
    
    // Check the widget status every three minutes
    function checkAgentStatus() {
        SnapEngage.getAgentStatusAsync(function(online) {
            if (online) {
                SnapEngage.showButton();
            } else {
                SnapEngage.hideButton();
            }
        });
    
        // Recursive call
        clearTimeout(tid);
    
        // Set another three minute time out
        tid = setTimeout(checkAgentStatus, threeMinutes);
    }
    

    As you may have guessed, you can call .getAgentStatusAsync() asynchronously.

    .getWidgetId()

    SnapEngage.getWidgetId();
    

    Sometimes it will be helpful to know the ID of the currently-active widget, especially if you use .setWidgetId() to change the active widget on the fly.

    No Parameters

    Returns

    // An example widget ID is returned from the call above
    '1z1z1z1z1-y2y2-x3x3-w4w4-v5v5v5v5v5v'
    
    Type Description
    String Returns a String that is the full widget ID of the currently active widget. (Alphanumeric plus dashes.)

    An example return value of is inside the code example.

    Example getWidgetId() Usage

    Send a system message to the agent based on the widget ID
    SnapEngage.setCallback('StartChat', function(email, msg, type) {
        var success = false;
        var tid;
    
        function sendWidgetName() {
            var currWidget = SnapEngage.getWidgetId();
    
            // For each different widget ID, send a message to the agent with that widget's name
            switch (currWidget) {
                case 'xxxxx-xxxx-xxxx-xxxx' :
                    success = SnapEngage.sendTextToChat('A Widget\'s Name');
                    break;
                case 'yyyyyy-yyyy-yyyy-yyyyy' :
                    success = SnapEngage.sendTextToChat('Other Widget\'s Name');
                    break;
                default :
                    success = SnapEngage.sendTextToChat('Error fetching Widget Name');
                    break;
            }
        }
    
        // Call the function above
        sendWidgetName();
    
        if (!success) {
            clearTimeout(tid);
    
            // Try again every two seconds until success.
            tid = setTimeout(sendWidgetName, 2000);
        }
    });
    

    Send a message to the agent that changes for each different widget ID. This code sample uses getWidgetId() along with the StartChat JavaScript event and sendTextToChat().

    .hideButton()

    SnapEngage.hideButton();
    

    Immediately hide the floating online/offline button.

    No Parameters

    .openProactiveChat()

    // Do not open proactive chat if the user has recently
    // closed a proactive invite
    var forced = false;
    
    // Do not open the offline box if the widget is not online
    var offlineFallback = false;
    
    // Do not open the offline box if the widget is not online
    var message = 'Hey there! How can I help you today?';
    
    // Regular chat box
    var minimizedView = false; 
    
    // Call the API with the above parameters
    SnapEngage.openProactiveChat(forced, offlineFallback, message, minimizedView);
    

    Manually open a proactive message.

    Parameters

    Parameter Type Description
    forced boolean Should SnapEngage disregard whether or not the visitor has recently closed a chat window? (See here for more info on The 30-minute Proactive Chat Delay Cookie.) And should SnapEngage disregard whether or not you have "Enable Proactive Chat" checked in your Admin Dashboard Proactive Settings tab? For example, if you're hooking this function to the onclick event of an tag, you'll want this set to true because you can assume someone clicking a link does want to chat.
    offlineFallback boolean Should this function fallback to the offline form if live chat is currently unavailable? For example, if you’re hooking this function to the onclick event of an tag, you'll want this set to true because you can assume someone clicking a link does want to get in touch with you, and if you’re offline this will give them the option of filling out the offline form. Alternatively: Be careful using true here, a poor implementation of the .openProactiveChat() function with offlineFallback set to true can be very jarring for your visitors!
    message String When calling .openProactiveChat() manually, you can also set a first message for the Proactive Chat. Otherwise the Proactive Chat message will fall back to the first available message from the Proactive Chat configuration of the widget. This message will appear to come from your agent, and will show up wherever you call this manually. So in most cases, the best option is to define a very generic message such as, "Thanks for visiting. How can I help you?"
    minimizedView boolean Should the visitor be prompted with the minimized Proactive Chat invite? See here for more info on minimized Proactive Chat. When no programmatic message is set in this prompt, the previous parameter should be set to 'undefined'.

    .sendTextToChat()

    // You MUST use sendTextToChat() inside the ChatMessageReceived callback
    // which ensures that there is an active chat before the message is sent.
    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
    
        // Send a message to the agent
        var text = 'Remember to mention the current promotion!';
        SnapEngage.sendTextToChat(text);
    
        // Now clear the ChatMessageReceived callback since you
        // just sent the message. (Otherwise, this callback will
        // send the message every time ChatMessageReceived fires)
        SnapEngage.setCallback('ChatMessageReceived', '');
    
    });
    

    Send a message to the active chat agent without showing it to the visitor. Optionally, add a second parameter of 'visitor' to send this message to the visitor.

    Parameters

    // You MUST use sendTextToChat() inside the ChatMessageReceived callback
    // which ensures that there is an active chat before the message is sent.
    SnapEngage.setCallback('ChatMessageReceived', function (agent, msg) {
    
        // Send a message to the visitor
        var text = 'Thanks for chatting! Here is a 10% off coupon code: TENOFF';
        SnapEngage.sendTextToChat(text, 'visitor');
    
        // Now clear the ChatMessageReceived callback since you
        // just sent the message. (Otherwise, this callback will
        // send the message every time ChatMessageReceived fires)
        SnapEngage.setCallback('ChatMessageReceived', '');
    
    });
    
    Parameter Type Description
    text String The text content of a message to be sent to the currently-active agent. When fired, the message will be sent to the agent but not to the visitor.
    to String Enter this optional parameter if you would like to send a message to the currently-active visitor and not to the agent.

    Parameter values

    to value
    the visitor, not the agent 'visitor'

    Return values

    // if the call above returns 'false', it means
    // there is an active chat and the message was
    // sent to the visitor.
    false
    
    Type Description
    boolean If true, there is an active chat and the message was sent to the agent. If false, there is an active chat and the message was sent to the visitor. Or, there is no active chat.

    .setButtonEffect()

    var negativePixels = '-4px';
    SnapEngage.setButtonEffect(negativePixels);
    

    Deprecated. This API method is not supported in the Design Studio. (If you are a legacy Style tab user, this API is supported).

    Set the non-hover button position for your button. (Direction is set automatically by your button’s position.)

    Parameters

    Parameter Type Description
    negativePixels String If you are a legacy Style tab user using a custom button image, and you would like to hide more of the button when it is not being hovered over, you can use this function to override the default positioning (which is '-4px'). The direction of the positioning is determined by your Admin Dashboard Style tab. (On-hover, the button’s position changes to ‘0px’).

    .setCallback()

    SnapEngage.setCallback(eventName, function (eventParameters) {
        console.log(eventParameters);
    });
    

    The method used to hook a function onto a SnapEngage JavaScript Event. For a full list of eventName and eventParameters, please reference the SnapEngage JavaScript Events documentation.

    Parameters

    Parameter Type Description
    eventName String The event on which to fire an anonymous function.
    Anonymous Function Function The second parameter of this function is an anonymous function. The anonymous function accepts various eventParameters which are detailed in the SnapEngage JavaScript Events documentation.

    .setChatFormPosition()

    // Set the legacy chatbox to pop up in the 'tl' (top left)
    // corner of the browser window
    var position = 'tl';
    SnapEngage.setChatFormPosition(position);
    

    Deprecated. This API method is not supported in the Design Studio. Design Studio users may change the position of the chat form by going to Chat Box -> Global Box Settings -> In-page Popup. (If you are a legacy Style tab user, this API is still supported).

    Manually set the position where you would like the chat window to appear. (Will not reposition an already-visible chat box.)

    This option can also be easily set in the legacy Style tab of the Admin Dashboard without the need for an API call. But you can use this function if you need to reposition the chat box in a special circumstance.

    Parameters

    Parameter Type Description
    position String A string representing the desired position of the legacy chat window. Requires specific values that are case-sensitive, see the table below of "Parameter Values".

    Parameter Values

    Position Value
    Bottom Right 'br'
    Bottom Left 'bl'
    Top Right 'tr'
    Top Left 'tl'
    Center 'c'

    .setCustomField()

    var fieldName = 'Company';
    var fieldValue = 'Vandelay Industries';
    
    SnapEngage.setCustomField(fieldName, fieldValue);
    

    Pre-populate any field on your prechat or offline form. (The field is still editable by the visitor.)

    For Design Studio users only. Legacy chat users may instead use the .setDescription(), .setUserEmail(), or .setUserName() API methods to pre-populate their non-custom form fields. Custom form users will be able to pre-populate any custom fields on their forms by simply using JavaScript, for example, document.getElementById("myFavoriteColor").value = "blue".

    Parameters

    Parameter Type Description
    fieldName String The field’s name attribute can be found by inspecting the DOM and looking for the input element’s name attribute. In general the name of a field is the field’s label with no spaces, and case-sensitive. For example, if you have a field with a label 'Favorite Color', the name attribute is 'FavoriteColor'.
    fieldValue String Provide a value for this field. You can hardcode the value, or pass it as a parameter using JavaScript or server-side scripting.

    .setDescription()

    var description = 'Hello! I need help!';
    SnapEngage.setDescription(description);
    

    Pre-populate the 'Description' field on the prechat form. (The description is still editable by the visitor.)

    Parameters

    Parameter Type Description
    description String The message you would like to pre-populate the description field with. The description will still be fully editable by your visitor, but this might make it easier for your agents to know what your visitors are asking after, since many visitors may not bother to enter a problem description or request in the first place.

    .setLocale()

    var languageCode = 'de';
    SnapEngage.setLocale(languageCode);
    

    Allows you to set the visitor chat to use a different language than the one you have set up in your Admin Dashboard. See table of Paramter Values for potential locales.

    Parameters

    Parameter Type Description
    languageCode String Set the locale manually using one of the available languages listed in the table below. Requires specific values that are case-sensitive, see the table below of "Parameter Values".

    Parameter values

    Language Value
    Arabic 'ar'
    Azerbaijini 'az'
    Chinese (Simplified) 'zh'
    Chinese (Traditional) 'zh_TW'
    Czech 'cs'
    Danish 'da'
    Dutch 'nl'
    English 'en'
    Estonian 'et'
    Finnish 'fi'
    French 'fr'
    French (Canadian) 'fr_CA'
    German 'de'
    Hebrew 'rw'
    Hungarian 'hu'
    Icelandic 'is'
    Italian 'it'v
    Japanese 'ja'
    Korean 'ko'
    Latvian 'lv'
    Lithuanian 'lt'
    Norwegian Bokmaal 'nb'
    Norwegian Nynorsk 'nn'
    Polish 'pl'
    Portuguese 'pt'
    Russian 'ru'
    Romanian 'ro'
    Slovak 'sk'
    Spanish 'es'
    Swedish 'sv'
    Turkish 'tr'

    .setNoProactiveChatDelay()

    // Delay the proactive invitation for 10 minutes
    var delayInMinutes = 10;
    SnapEngage.setNoProactiveChatDelay(delayInMinutes);
    

    Disable or alter the amount of time that proactive invitations remain disabled for any visitor who closes a chat window. The default proactive invitation delay (without using this API) is 30 minutes.

    Parameters

    Parameter Type Description
    delayInMinutes Integer By default, we think that if a visitor closes a chat window, they are either not interested in chatting or done chatting. In order to avoid bombarding them with proactive invitations we set a cookie to disable proactive invitations for that visitor for 30 minutes by default. You can alter that amount of time with this function. (To use a session cookie, set to 0.)

    .setProactiveAutoCloseDelay()

    // Autoclose the proactive invitation after 5 minutes of inactivity
    var minutes = 5;
    SnapEngage.setProactiveAutocloseDelay(minutes);
    

    Adjust the time before the proactive invitation disappears. The default proactive autoclose delay is 2 minutes.

    By default, the proactive chat window is set to close after 2 minutes of inactivity, that is: if a visitor does not respond for a couple minutes, we generally assume that they are not interested in chatting. If you never want the proactive invitation to disappear, set the parameter to 0.

    Parameters

    Parameter Type Description
    minutes Integer Number (in minutes) until auto-close. This can be a whole number or decimal (eg. 0.5 can be used for a delay of 30 seconds).

    .setUserEmail()

    var email = '[email protected]';
    
    // Set the email field
    SnapEngage.setUserEmail(email);
    
    // Do the same as above AND make the email field read-only
    // i.e. not editable for the visitor
    SnapEngage.setUserEmail(email, true);
    

    This API will do three things:

    First, it pre-populates the 'email' field on your prechat or offline form (if this field exists).

    Second, this API will provide a visitor’s email address to an agent who takes the chat. The email gets stored on the conversation (case) and will be passed to your integration at the close of the case.

    Third, on submit of a prechat or offline form, a cookie will be stored in the visitor's browser called 'SnapABugUserEmail' to repeat this same behavior on future chats. Read more about the SnapABugUserEmail cookie here.

    Parameters

    Parameter Type Description
    email String A non-encoded email address, for example, '[email protected]'. You will need to use your local environment to deliver the email address to this function, either through server-side scripting or JavaScript.
    locked boolean An optional parameter. If set to true, the email field will be locked i.e. read-only and the visitor will not be able to edit the field. If set to false, the email field will not be read-only and the visitor will be able to edit the field (this is the default).

    .setUserName()

    var name = 'Arya Stark';
    SnapEngage.setUserName(name);
    

    This API will do four things:

    First, it pre-populates the 'name' field on your prechat or offline form (if this field exists).

    Second, it updates the visitor alias that is displayed in the chatbox chat transcript.

    Third, this API will provide the visitor’s name to the agent who takes the chat. If the user's email is known, SnapEngage will update the database contact with this name (note: see green box below).

    Fourth, this API stores a cookie in the visitor's browser called 'SnapABugUserAlias'1 to repeat this same behavior on future chats. Read more about the SnapABugUserAlias cookie here.

    1 This cookie was previously known as the 'SnapABugUserName' cookie which is now deprecated.

    Parameters

    Parameter Type Description
    name String A non-encoded name, for example, Arya Stark. You will need to use your local environment to deliver the name to this function, either through server-side scripting or JavaScript.

    .setWidgetId()

    DEPRECATED as of March 12th 2018. See switchWidget() for improved functionality.

    var widgetId = '1234-5678-91011-1213-1415'
    SnapEngage.setWidgetId(widgetId);
    

    Manually set the currently-active widget. A common use case would be offering chat buttons which are linked to separate widgets on a single page; for instance, creating one link that goes to your Help Desk widget, and another that goes to your Sales Team widget. Learn how to set that up right here.

    Parameters

    Parameter Type Description
    widgetId String The widget ID that you would like to dynamically set as the active widget on your website. You can find your widget ID inside the Admin Dashboard's Settings, by clicking the Get the Code tab. Scroll to the '(Advanced) Widget ID' section.

    .showButton()

    SnapEngage.showButton();
    

    Show the floating online or offline button defined in your Design Studio theme (or for legacy users, the button set up in your Style tab).

    No Parameters

    .startChat()

    var msg = 'Hey there, do you need help learning about' +
    ' The Invigaron System?';
    SnapEngage.startChat(msg);
    

    Start a chat session and send a manually defined message to the visitor.

    Parameters

    Parameter Type Description
    msg String A string containing the first chat message to be sent to the visitor when this function fires.
    SnapEngage.startLink();
    
    // You can also use this JavaScript method inside the onclick attribute
    // of an <a> tag on your page. When a visitor clicks this link, it will fire
    // SnapEngage.startLink() and open the chat box.
    <a href="#" onclick="SnapEngage.startLink();">Chat with us!</a>
    

    The default method for starting a chat from an on-page <a> link's onclick event.

    No Parameters

    .switchWidget()

    var newWidgetId = "1234-5678-91011-1213-1415";
    var switchCallback = function() {
        // do something
    };
    
    SnapEngage.switchWidget(newWidgetId, switchCallback);
    

    Enable switching between two widgets.

    We have deprecated the setWidgetId() API to provide a better solution for switching between two widgets and returning a more accurate status to help with your business needs. Additionally, we now offer an optional callback parameter so you can do more when the new status is returned. Here we do not differentiate between online and offline status, however, you can use the getAgentStatusAsync API to call different methods based on the new status.

    Parameters

    Parameter Type Description
    newWidgetId String Required. Must be a valid SnapEngage Widget ID (‘xxxx-xxxx-xxxx-xxx-xxxx’). The new WidgetID you would like to activate. Learn how to set that up here.
    switchCallback Anonymous Function A predefined function that will get called after our system completes checking the newWidgetId status.

    Returns

    Type Description
    Boolean Will return false with console warning ONLY if the newWidgetId parameter is not provided. Otherwise no return value provided.

    Example switchWidget() Usage

    // Setup required parameters
    var newWidgetId = "1234-5678-91011-1213-1415";
    var switchCallback = function() {
        SnapEngage.getAgentStatusAsync(function(online) {
            if (online) {
                console.log("Chat available");
            } else {
                console.log("Chat offline");
            }
        });
    };
    
    // Now call the API
    SnapEngage.switchWidget(newWidgetId, switchCallback);
    

    .endChat()

    var options = { closeChatBox: true };
    SnapEngage.endChat(options);
    

    Forces chat to end.

    Parameters

    Parameter Type Description
    options object An object containing options

    Options object

    property Type Description
    closeChatBox boolean Whether to close or not chat box

    Returns

    Type Description
    void this method doesn't return anything

    Example endChat() Usage

    Force chat box to close when a chat ends.

    var event = SnapEngage.callbacks.CHAT_ENDED;
    function callback() {
      SnapEngage.endChat({ closeChatBox: true });
    }
    SnapEngage.setCallback(event, callback);