Web Messenger

The Sunshine Conversations Web Messenger is a highly customizable messaging widget that can be added to any web page. Web Messenger is unique in that it allows the user seamlessly move the conversation beyond the browser to a persistent channel like SMS, Facebook Messenger, or any other OTT channels.

Current version: v

Capabilities

The Web Messenger supports a wide variety of capabilities as seen in the channel capabilities grid. Below is a detailed view of each capabilities.

Content Types

  • Text

    Full SupportAPI
  • Image

    Full SupportAPI
  • File

    Full SupportAPI
  • Emoji

    Full SupportAPI
  • GIF

    Partial SupportAPI
  • Location

    Partial SupportAPI

Action Types

  • Link

    Full SupportAPI
  • Extension

    Full SupportAPI
  • Buy

    Full SupportAPI
  • Postback

    Full SupportAPI
  • Reply

    Full SupportAPI
  • Location Request

    Full SupportAPI

Structured Messages

  • Compound Message

    Full SupportAPI
  • Carousel

    Full SupportAPI
  • Form

    Full SupportAPI

Indicators

  • Typing

    Full SupportAPI
  • Read

    Full SupportAPI
  • Conversation Start

    Full SupportAPI

Delivery Events

Delivery events allow you to track deliveries of Sunshine Conversations messages to the Web Messenger by subscribing to the message:delivery:channel webhook.

Badge for unread messages

Badge for Unread Messages

When the user receives new messages, a badge containing the count of unread messages is displayed in the header of the Web Messenger if the user’s view is not at the bottom of the conversation.

The badge is removed when the messages are marked as read with the following user actions:

  • Scroll to bottom of conversation
  • Focus or type in the chat input
  • Click on the Web Messenger header or badge
  • Click on the Web Messenger widget
  • Send a message from a linked channel

Note that unless the user sends a message from a linked channel, no other user actions may remove the badge while the user is viewing the settings.

It is possible for the appMaker to remove the badge by marking the messages as read using the markAllAsRead, open and close SDK API methods, as well as calling the /conversation/read REST API endpoint.

An unreadCount webhook event is also triggered when the number of unread messages changes.

Carousels are rendered natively with full functionality in the Web Messenger. See our API documentation for instructions on how to send one.

Carousel web

Carousels support up to a maximum of 10 message items. Each message item must include a title and at least one supported action. Optionally, an image and description can be included as well. Images can be displayed in two different aspect ratios, “square” and “horizontal”. For more information, see our API documentation.

Carousel items with “horizontal” images (default):

Carousel Web horizontal

Carousel items with “square” images:

Carousel Web square

Supported actions

The Web Messenger supports the following action types in a carousel message item:

  • Link
  • Postback
  • Buy
  • Webview

List message fallback

If the Web Messenger receives a list type message, it will display a carousel instead.

Location

Location messages are rendered as text with a Google Maps link of the location.

Users can send location messages as a response to a Location Request, or by using the Share Location button.

Forms

Form messages are rendered natively with full functionality in the Web Messenger and are a great way for you to capture user data.

Form Examples

A form message may only be sent by the appMaker via the API or template syntax. It is also possible to block the conversation and resume it only once the user has fully filled the form. See our API documentation for instructions on how to send one.

Form Disabled Chat Input

You can see it in action right now by using our example template syntax, %((template: lead_capture))%.

Form Fields

Forms fields are always required and may be of type text, email and select. Each field must include a name, a label and a type. An optional placeholder may be specified for each field type.

Fields of type text and email come with integrated validation. Text fields support up to 128 characters, and a different range may be specified using the optional field attributes minSize and maxSize. Email fields are validated according to RFC 5322.

Form Field Error Validation

Forms support up to a maximum of 20 fields, with the select field supporting up to 20 options. Note that we currently support single selection only.

Receiving a Form Response

When an appUser fills the form, each field gets validated and locked. Once all fields are filled, a message of type formResponse is sent with the role appUser. The original appMaker form becomes locked and gets updated, each field now containing the appUser answer.

Form Completed

For more information on the formResponse message type, see our API documentation.

Prechat Capture

Prechat Capture is an add-on built by which leverages our new form message type and allows you to capture a user’s name and email before the start of a conversation.

When enabled, the chat input is disabled and the user is greeted by a welcome message and a form asking for their name and email. Once the form is successfully submitted, a thank you message is sent to the user and the conversation is then initialized, connecting the user to your business.

Prechat Capture

If your app has a Mailgun integration, the email captured is automatically linked with the user profile.

If your app has the Office Hours add-on enabled, the away message will be sent upon the first appUser message following the successful submission of the prechat capture form.

Prechat Capture Office Hours

Configuration

To enable the prechat capture experience, simply do so via the Web SDK init parameter as follows:

<script>
    Smooch.init({
        appId: '<app-id>',
        prechatCapture: {
            enabled: true,
            enableEmailLinking: true
        }
    })
        .then(
            function() {
                // Your code after init is complete
            },
            function(err) {
                // Something went wrong during initialization
            }
        );
</script>

Custom Prechat Capture

A custom Prechat Capture form may also be configured by setting the fields property to an array of form fields. For more information on fields, see our API documentation.

Custom Prechat Capture

Note that if you specify custom fields and enable the enableEmailLinking option, the first field of type email will be used for the email linking process. If no such field exists, the linking will not happen.

Here is an example on how to set a custom Prechat Capture form:

<script>
    Smooch.init({
        appId: '<app-id>',
        prechatCapture: {
            enabled: true,
            enableEmailLinking: true,
            fields: [
                {
                    type: 'email',
                    name: 'email',
                    label: 'Email',
                    placeholder: 'your@email.com'
                },
                {
                    type: 'text',
                    name: 'company-website',
                    label: 'Company website',
                    placeholder: 'mycompany.com'
                },
                {
                    type: 'select',
                    name: 'company-size',
                    label: 'Company size',
                    placeholder: 'Choose a number...',
                    options: [
                        {
                            name: '1-10',
                            label: '1-10 employees'
                        },
                        {
                            name: '11-50',
                            label: '11-50 employees'
                        },
                        {
                            name: '51+',
                            label: '51+ employees'
                        }
                    ]
                }
            ]
        }
    })
        .then(
            function() {
                // Your code after init is complete
            },
            function(err) {
                // Something went wrong during initialization
            }
        );
</script>

See our documentation on GitHub for more information on the different prechatCapture options.

Receiving the Response

Upon successful submission of the prechat capture form, a conversation is initialized with four messages:

  1. The Greeting message of type text;
  2. The Data Capture Form message of type form;
  3. The Confirmation message of type text; and
  4. The Data Capture Form Response message of type formResponse.

You may handle those messages like you would handle any other message.

Moving to other channels

Web Messenger allows users to continue a conversation on the messaging app of their choosing. After sending their first message, they will be prompted to be notified inside other apps when they get a reply. This takes pressure off of the business to reply instantly and allows the user to close their browser session without having to worry about missing a response.

Be Notified Inside Other Apps

For example, if a user visits your site and would like to close the tab, they can choose to ‘Connect’ to Messenger. This will connect their conversation to Facebook Messenger and enable notifications there.

Send to Messenger

When you reply to your user, will intelligently detect which messaging channel they most recently used and make sure they don’t get spammed with push notifications if they elect to be notified on multiple apps.

The current supported list of notifiable channels is as follows:

  • Facebook Messenger
  • Twilio
  • MessageBird
  • Mailgun
  • WeChat
  • Telegram
  • Viber
  • WhatsApp

In order to offer these channels, simply integrate any you want and they will be added to the list by default. You may also edit that list through the Update Integration API.

Getting notified by email

Be Notified By Email

In order to maintain the privacy and security of your user’s conversations, when an app user chooses to be notified over email, will create a separate, isolated client for that email thread. Only future replies to that email thread will be added to that conversation. This mitigates the danger of a malicious user attempting to claim ownership of someone else’s address.

The email to conversation mapping follows this logic:

If a user emails your business:

  • Future emails from that address (regardless of thread) will be routed to the same conversation.

If you link a given app user to an address via the linking API:

  • Future emails from that address (regardless of thread) will be routed to the same conversation.

If a user opts in to continue their conversation over email:

  • Future emails sent from the notification email thread will be routed to the same conversation.
  • Future emails sent from that address in a new thread will be routed to a new conversation.

Browser support

Web Messenger supports all popular browsers.

Desktop

  • Chrome: Latest and one major version behind
  • Edge: Latest and one major version behind
  • Firefox: Latest and one major version behind
  • Internet Explorer: 11+
  • Safari: Latest and one major version behind

Mobile

  • Stock browser on Android 4.1+
  • Safari on iOS 8+
<meta name="viewport" content="width=device-width, initial-scale=1">

Other browsers

Web Messenger is likely compatible with other and older browsers but we only test against the versions above.

Installation

There are a few ways you can include the Web Messenger on your web page.

The easiest way to get started is using the Script Tag method, but you can also include it using npm.

Script Tag Method

Step 1: Include the Web Messenger on your web page

Add the following code towards the end of the head section on your page and replace <app-id> with your app ID found in your app settings page.

<script>
    !function(e,n,t,r){
        function o(){try{var e;if((e="string"==typeof this.response?JSON.parse(this.response):this.response).url){var t=n.getElementsByTagName("script")[0],r=n.createElement("script");r.async=!0,r.src=e.url,t.parentNode.insertBefore(r,t)}}catch(e){}}var s,p,a,i=[],c=[];e[t]={init:function(){s=arguments;var e={then:function(n){return c.push({type:"t",next:n}),e},catch:function(n){return c.push({type:"c",next:n}),e}};return e},on:function(){i.push(arguments)},render:function(){p=arguments},destroy:function(){a=arguments}},e.__onWebMessengerHostReady__=function(n){if(delete e.__onWebMessengerHostReady__,e[t]=n,s)for(var r=n.init.apply(n,s),o=0;o<c.length;o++){var u=c[o];r="t"===u.type?r.then(u.next):r.catch(u.next)}p&&n.render.apply(n,p),a&&n.destroy.apply(n,a);for(o=0;o<i.length;o++)n.on.apply(n,i[o])};var u=new XMLHttpRequest;u.addEventListener("load",o),u.open("GET","https://"+r+".webloader.smooch.io/",!0),u.responseType="json",u.send()
    }(window,document,"Smooch","<app-id>");
</script>

Step 2: Initialize with your new app ID

Once has been included on your web page, you’re almost done. Simply initialize the Web Messenger using this code snippet

<script>
    Smooch.init({ appId: '<app-id>' })
        .then(
            function() {
                // Your code after init is complete
            },
            function(err) {
                // Something went wrong during initialization
            }
        );
</script>

NPM method

npm install smooch

In your code:

var Smooch = require('smooch');

Smooch.init({ appId: '<app-id>' }).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Keeping up to date

Web Messenger is frequently updated. Your installation is automatically kept up to date while using the script tag installation method. Using npm, you can upgrade to the latest version by running npm update smooch or changing the version of smooch in the dependencies section of your package.json file.

Each versions are posted as releases in the Web Messenger GitHub repository with corresponding release notes.

To receive an email when a new version is published, you can use GitPunch to subscribe to release updates:

  • Open https://gitpunch.com/
  • In the search box, enter https://github.com/smooch/smooch-web and select smooch/smooch-web from the autocomplete pane.
  • Using the blue slider, select which type of release (All, Patch, Minor, Major) you want to be notified about.
  • Click on “GitHub Sign In” to create a GitPunch account using your GitHub login or click “Enter Email” to signup with an email address and password.

Once configured, you’ll start receiving emails similar to the one below when new versions are published.

Web Messenger release email

Region configuration

Web messenger is supported in the following regions:

RegionRegion identifier
United StatesLeave unspecified
European Unioneu-1

To target the EU region for example the region identifier is passed to Smooch.init():

<script>
    Smooch.init({
      appId: '<app-id>',
      region: 'eu-1'
    })
        .then(
            function() {
                // Your code after init is complete
            },
            function(err) {
                // Something went wrong during initialization
            }
        );
</script>

Login with userId and JWT

After has initialized, your user can start sending messages right away. These messages will show up on the business side under a new appUser. However, these appUsers will not yet be associated to any user record you might have in an existing user directory.

If your application has a login flow, or if a user needs to access the same conversation from multiple devices, this is where the login method comes into play. You can associate users with your own user directory by assigning them a userId. You will then issue each user a jwt credential during the login flow. You can read more about this in the Authenticating users section.

Authentication delegate

The Web Messenger offers an onInvalidAuth which will be called when an invalid authentication token has been sent to . It allows you to provide a new token for all subsequent requests. The request that originally failed will be retried up to five times.

Smooch.init(SmoochOptions).then(function () {
    Smooch.setDelegate({
        onInvalidAuth() {
            return new Promise((resolve) =>
                resolve('my-new-auth-token')
            );
        }
    });
});

See Expiring JWTs on SDKs for more information.

Files

The Web Messenger has full native support for sending and receiving files. See our API documentation for instructions on how to send one.

Customization

The Web Messenger includes a set of built-in customization options which you can leverage in 3 ways:

  • Via the Update Integration API.
  • Using the dashboard to manually set styling options in the Web messenger settings page.
  • Passing in styling settings in the call to the Smooch.init method.

Embedded mode

Supported by the Smooch.init method.

To embed the widget in your existing markup, you need to pass embedded: true when calling Smooch.init. By doing so, you are disabling the auto-rendering mechanism and you will need to call Smooch.render manually. This method accepts a DOM element which will be used as the container where the widget will be rendered.

Smooch.init({
    appId: '<app-id>',
    embedded: true
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Smooch.render(document.getElementById('chat-container'));

Strings customization

Supported by the Smooch.init method.

The Web Messenger lets you customize any strings it displays by overwriting its keys. Simply add the customText key in your Smooch.init call and specify new values for the keys used in . You can find all available keys here. If some text is between {}, or if there is an html tag such as <a>, it needs to stay in your customized text.

For example:

Smooch.init({
    appId: '<app-id>',
    customText: {
        headerText: 'How can we help?',
        inputPlaceholder: 'Type a message...',
        sendButtonText: 'Send'
    }
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Date localization

Supported by the Smooch.init method.

When using strings customization to translate the interface, you will also want to have Web Messenger show the date and time in the right language. To do this, simply pass locale at initialization time. You might also want to override the timestamp format to match your language. You can learn more about formats here.

Smooch.init({
    appId: '<app-id>',
    locale: 'fr-CA'
    customText: {
        // ...
        conversationTimestampHeaderFormat: 'Do MMMM YYYY, hh:mm',
        // ...
    }
})
    .then(
        function() {
            // Your code after init is complete
        },
        function(err) {
            // Something went wrong during initialization
        }
    );

Display Style

Supported by the Smooch.init method, the Web Messenger settings page in the dashboard, and the Update Integration API.

The Web Messenger can be displayed as a button or as a tab. The default style is the button mode.

When the display style is a button, you have the option of selecting your own button icon. The image must be at least 200 x 200 pixels and must be in either JPG, PNG, or GIF format.

Smooch.init

Specify the displayStyle and buttonIconUrl in the call to Smooch.init.

Smooch.init({
    appId: '<app-id>',
    // ...
    displayStyle: 'button',
    buttonIconUrl: 'https://myimage.png'
    // ...
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Button Size

Supported by the Smooch.init method, and the Update Integration API.

You can customize the size of the button by setting a buttonWidth and buttonHeight. When not provided, the button will have a default size of 58 x 58 pixels.

Smooch.init

Specify the buttonWidth and buttonHeight in the call to Smooch.init.

Smooch.init({
    appId: '<app-id>',
    // ...
    buttonWidth: '90',
    buttonHeight: '90'
    // ...
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Fixed Intro

Supported by the Smooch.init method, and the Update Integration API.

You can set the introduction pane to fixed mode by setting fixedIntroPane to true. When set, the pane will be pinned at the top of the conversation instead of scrolling with it. The default value is false.

Default
Fixed

Smooch.init

Smooch.init({
    appId: '<app-id>',
    // ...
    fixedIntroPane: true
    // ...
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Colors

Supported by the Smooch.init method, the Web Messenger settings page in the dashboard, and the Update Integration API.

The supported color customizations are:

  • The Brand Color customizes the color of the messenger header. It is also used for the color of the button or tab in idle state, as well as the color of the default app icon. If no color is specified, the brand color will default to #65758e.
  • The Conversation Color customizes the color of customer messages and actions in the footer. If no color is specified, the conversation color will default to #0099ff.
  • The Action Color changes the appearance of links and buttons in your messages. It is also used for the ‘Send’ button when it is in active state. If no color is specified, the action color will default to #0099ff.
Color Customization

Smooch.init

Smooch.init({
    appId: '<app-id>',
    // ...
    customColors: {
        brandColor: "7af442",
        conversationColor: "b7b7b5"
        actionColor: "191919"
    }
    // ...
})
    .then(
        function() {
            // Your code after init is complete
        },
        function(err) {
            // Something went wrong during initialization
        }
    );

Business profile

Supported by the Smooch.init method, and the Update Integration API.

You can customize your business branding with the businessName and businessIconUrl settings. For the businessIconUrl setting, the image must be at least 200 x 200 pixels and must be in either JPG, PNG, or GIF format.

Web Messenger Business Branding

Smooch.init

Smooch.init({
    appId: '<app-id>',
    // ...
    businessName: 'Acme Corporation',
    businessIconUrl:
        'https://is2-ssl.mzstatic.com/image/thumb/Purple127/v4/67/a4/5b/67a45b68-c821-842f-22f5-9fa83b605ce3/mzl.evidoiah.jpg/1200x630bb.jpg'
    // ...
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Background Image

Supported by the Smooch.init method, and the Update Integration API.

You can customize the background image in your SDK with the backgroundImageUrl setting. The image will be displayed at its full size, and tiled if it is not large enough to fill the conversation.

For reference, the following CSS will be used to display the background:

 {
    background-image: url('https://a-nice-texture.png');
}

Web Messenger Business Branding

Smooch.init

Smooch.init({
    appId: '<app-id>',
    // ...
    backgroundImageUrl: 'https://a-nice-texture.png'
    // ...
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Sound notification

Supported by the Smooch.init method.

By default, a sound notification will be played when a new message comes in and the window is not in focus.

To disable this feature, you need add the soundNotificationEnabled option to the Smooch.init call, like this:

Smooch.init({
    appId: '<app-id>',
    soundNotificationEnabled: false // Add this line to your 'Smooch.init' call
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Browser storage

Supported by the Smooch.init method.

By default, the Web Messenger will store the identity of anonymous users in the localStorage of the browser.

Using the localStorage will persist the user identity through out browser sessions (including page reloads and browser restarts). To clear the user identity once the browser is closed, use sessionStorage instead. Learn more

Smooch.init({
    appId: '<app-id>',
    browserStorage: 'sessionStorage' // Add this line to your 'Smooch.init' call
}).then(
    function() {
        // Your code after init is complete
    },
    function(err) {
        // Something went wrong during initialization
    }
);

Supported by the Smooch.init method.

The Web Messenger features a menu that allows the user to send various message types. The types displayed in this menu can be customized, or the menu can be hidden altogether.

If you want to control this menu, add the menuItems option to the Smooch.init call:

Smooch.init({
    appId: <app-id>,
    menuItems: {
      imageUpload: true,
      fileUpload: true,
      shareLocation: true
    },
    // ...
})
    .then(
        function() {
            // Your code after init is complete
        },
        function(err) {
            // Something went wrong during initialization
        }
    );

Menu Options

To hide the menu completely, override the menuItems option as follows:

Smooch.init({
    appId: <app-id>,
    menuItems: {},
    // ...
})
    .then(
        function() {
            // Your code after init is complete
        },
        function(err) {
            // Something went wrong during initialization
        }
    );

Menu Options

Filtering and transforming messages

The Web Messenger allows you to filter and transform messages by using the beforeDisplay delegate. To set a delegate, use the setDelegate method.

This may be useful if you want to conditionally filter specific messages or transform their structure. See the Message Schema section to learn more on the message properties that you can access and modify. You may also want to set your own properties using the beforeSend delegate.

Filtering messages

The following example sets a beforeDisplay delegate method to check if a message has been marked as archived in the metadata (this can be done using the beforeSend delegate method for example). If the field isArchived is true, we instruct the SDK to hide the message by returning null. If not, we simply return the original message unmodified.

const delegate = {
    beforeDisplay(message) {
        if (message.metadata && message.metadata.isArchived) {
            return null;
        }

        return message;
    }
};

Smooch.init({
    appId: <app-id>,
    delegate
})

Transforming business messages

The following example sets a default author name on messages that lacks one if they are originating from the business. We first check if the message is sent by the appMaker and if a name has been specified. If not, we set it and return the modified message.

const delegate = {
    beforeDisplay(message) {
        if (message.role === 'appMaker' && !message.name) {
            message.name = 'Acme Bank';
        }

        return message;
    }
};

Smooch.init({
    appId: <app-id>,
    delegate
})

Transforming user messages

The following example adds the URL of the page the user is visiting while messaging a business. This can be useful when users navigate within a site while messaging. We first check if the message role is appUser and then add a currentUrl attribute in the metadata property.

const delegate = {
    beforeSend(message) {
        if (message.role === 'appUser') {
            message.metadata = {
                ...message.metadata,
                currentUrl: window.location.href
            };
        }

        return message;
    }
};

Smooch.init({
    appId: <app-id>,
    delegate
})

Transforming postback

The following example adds the URL of the page the user is visiting while actioning a postback. This can be useful to tailor the reaction to the postback in accordance to the current page. We add a currentUrl attribute in the metadata property.

const delegate = {
    beforePostbackSend(postback) {
        postback.metadata = {
            ...postback.metadata,
            currentUrl: window.location.href
        };

        return postback;
    }
};

Smooch.init({
    appId: <app-id>,
    delegate
})

Whitelisting Domains

By default, the Web Messenger can be initialized from any domain with the use of the appId. To limit domains where Web messenger can be used, you can use the originWhitelist setting in the Update Integration API.

When the originWhitelist is set, restricts the access to only the origins listed in the array by implementing Cross Origin Resource Sharing (CORS). More specifically, it will look at the Origin header for every HTTP request and block it if the Origin is not part of the originWhitelist array.

Notes:

  • localhost is supported as a valid hostname in the origin, so you can test when doing local development.
  • Wildcard subdomains are not currently supported, so you need to list all of your supported domains individually.

Content Security Policy

If your deployment requires CSP compatibility, add the following meta tag to your configuration.

<meta http-equiv="Content-Security-Policy" content="
    connect-src
        wss://*.smooch.io
        https://*.smooch.io;
    font-src
        https://*.smooch.io;
    script-src
        https://*.smooch.io;
    style-src
        https://*.smooch.io;
    img-src
        blob:
        https://*.smooch.io;">

Note that an equivalent configuration can be done server side.

According to the channels you use, other domains may need to be added:

These are used to display QR codes to link the Web Messenger conversation

This is used to allow buy actions from the Web Messenger:

Note that your CSP configuration should also include any domains used to host images or files sent in messages. If you require blob: to be excluded for img-src, you must disable the image upload feature via the init settings.

Implementing your own User Interface

If you need more customization options than those supported natively by , you can implement a complete custom UI by leveraging events and APIs exposed by the SDK, which will continue to facilitate the connection with the platform.

Our sample custom UI project covers the first steps you need to follow to get started.