smooch

Smooch.io powered web messaging

Usage no npm install needed!

<script type="module">
  import smooch from 'https://cdn.skypack.dev/smooch';
</script>

README

Smooch Web Messenger

npm version

Smooch is the best way to have personal, rich conversations with people on your website or customers on any device. Our features, integrations and developer-friendly APIs empower companies to connect with their customers in a whole new way.

The Smooch Web Messenger will add live web messaging to your website or web app. Customers will be able to talk to you from your website, while you manage conversations using your favorite business systems.

  • Let your customers talk to you the way they want by seamlessly moving web chat conversations to any messaging app.
  • Sync conversations across every device and channel your customers use.
  • Build better relationships with messaging that feels and looks tailored to your website.
  • Delight your customers with the most engaging conversational experience using rich messaging.
  • Maximize development productivity with a single codebase across platforms and add more channels anytime.
  • Bring every conversation into your existing business systems. No new tool to learn. See all integrations.
  • Allow multiple users to participate in a conversation with each other along with the business actor.

Note: this document is for version 5.0.0. If you are upgrading please see the release notes here.

Usage

Script Tag

Add the following code towards the end of the <head> section on your page and replace <integration-id> with your integration id at the end of the script. You may replace "5" with any version from 4.0.0 onwards, or with a major version (i.e.: "4" or "5") to load that specific version of the Web SDK. If a version is included without specifying the patch, the latest version of the specified major release will be loaded. If an invalid version is passed an error will be thrown and the Web SDK will fail to load.

<script>
    !function(o,d,s,e,f){var i,a,p,c=[],h=[];function t(){var t="You must provide a supported major version.";try{if(!f)throw new Error(t);var e,n="https://cdn.smooch.io/",r="smooch";e="string"==typeof this.response?JSON.parse(this.response):this.response;var o=f.match(/([0-9]+)\.?([0-9]+)?\.?([0-9]+)?/),s=o&&o[1],i=o&&o[2],a=o&&o[3],p=e["v"+s],c=e["v"+s+"."+i+".patch"];if(e.url||p||c){var h=d.getElementsByTagName("script")[0],u=d.createElement("script");if(u.async=!0,a)u.src=c||n+r+"."+f+".min.js";else{if(!(5<=s&&p))throw new Error(t);u.src=p}h.parentNode.insertBefore(u,h)}}catch(e){e.message===t&&console.error(e)}}o[s]={init:function(){i=arguments;var t={then:function(e){return h.push({type:"t",next:e}),t},catch:function(e){return h.push({type:"c",next:e}),t}};return t},on:function(){c.push(arguments)},render:function(){a=arguments},destroy:function(){p=arguments}},o.__onWebMessengerHostReady__=function(e){if(delete o.__onWebMessengerHostReady__,o[s]=e,i)for(var t=e.init.apply(e,i),n=0;n<h.length;n++){var r=h[n];t="t"===r.type?t.then(r.next):t.catch(r.next)}a&&e.render.apply(e,a),p&&e.destroy.apply(e,p);for(n=0;n<c.length;n++)e.on.apply(e,c[n])};var n=new XMLHttpRequest;n.addEventListener("load",t),n.open("GET","https://"+e+".webloader.smooch.io/",!0),n.responseType="json",n.send()}(window,document,"Smooch","<integration-id>","5");
</script>

then initialize the Web Messenger by placing this snippet towards the end of the body section of your page.

<script>
    Smooch.init({ integrationId: '<integration-id>' }).then(function () {
        // Your code after init is complete
    });
</script>

Browserify and Webpack

Install from npm

npm install --save smooch

Require and init

var Smooch = require('smooch');

Smooch.init({ integrationId: '<integration-id>' }).then(function () {
    // Your code after init is complete
});

Browser support

Web Messenger supports all popular browsers.

Desktop versions

  • 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 versions

  • Stock browser on Android 4.1+
  • Safari on iOS 8+

Other browsers

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

API

Individual functions

init(options)

Initializes the Smooch widget in the web page using the specified options. It returns a promise that will resolve when the Web Messenger is ready. Note that except on and off, all methods needs to be called after a successful init.

Options
Option Optional? Default value Description
integrationId No - Your integration id
externalId Yes - Optional. User's external id, which can be passed in init() as an alternative to login() (see below)
jwt Yes - Optional. User's authentication token, which can be passed in init() as an alternative to login() (see below)
authCode Yes - An auth code for linking to an existing conversation (see more details here)
locale Yes en-US Locale used for date formatting using the <language>-<COUNTRY> format. Language codes can be found here and country codes here.
**Note 1 : ** The country part is optional, and if a country is either not recognized or supported, it will fallback to using the generic language. If the language isn't supported, it will fallback to en-US.
Note 2: this is only used for date formatting and doesn't provide built-in translations for Web Messenger. Refer to the documentation for how to handle translations.
soundNotificationEnabled Yes true Enables the sound notification for new messages
imageUploadEnabled Yes true Enables the image upload feature. (deprecated: use menuItems.imageUpload; if this option is false, it will disable menuItems.imageUpload and menuItems.fileUpload)
fixedHeader Yes false When enabled, the introduction pane will be pinned at the top of the conversation instead of scrolling with it.
embedded Yes False Tells the widget it will be embedded. (see Embedded section below)
displayStyle Yes button Choose how the messenger will appear on your website. Must be either button or tab.
buttonIconUrl Yes - When the displayStyle is 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.
buttonWidth Yes 58px When the displayStyle is button, you have the option of specifying the button width.
buttonHeight Yes 58px When the displayStyle is button, you have the option of specifying the button height.
businessName Yes - A custom business name.
businessIconUrl Yes - A custom business icon url. The image must be at least 200 x 200 pixels and must be in either JPG, PNG, or GIF format.
backgroundImageUrl Yes - A background image url for the conversation. Image will be tiled to fit the window.
integrationOrder Yes - Array of integration IDs. When set, only integrations from this list will be displayed. If an empty array is used, no integrations will be displayed. Note: Listing an integration in the array doesn't guarantee that it will be displayed in the Web Messenger.
customColors Yes See below. Colors used in the Web Messenger UI.
customText Yes See the example below Strings used in the Web Messenger UI. You can use these to either customize the text or translate it. Note: Some strings include variables (surrounded by {}) which must remain in your customized text.
menuItems Yes See below. Choose menu items.
notificationChannelPromptEnabled Yes true Enables displaying a prompt to new users after their first message to suggest linking their chat instance with their other 3rd-party apps.
browserStorage Yes localStorage Choose the storage type to use for storing user identity in the browser. Must be either localStorage or sessionStorage. Learn more
delegate Yes undefined Sets a delegate on the conversation. See the delegate section for more details.
prechatCapture Yes See below. Enables automatically capturing a user's name and email via a form before the start of a conversation. Disables the chat input until the form has been submitted.
canUserSeeConversationList Yes true Allows users to view their list of conversations.
customColors
Option Optional? Default value Description
brandColor Yes 65758e This color will be used in the messenger header and the button or tab in idle state. Must be a 3 or 6-character hexadecimal color.
conversationColor Yes 0099ff This color will be used for customer messages, quick replies and actions in the footer. Must be a 3 or 6-character hexadecimal color.
actionColor Yes 0099ff This color will be used for call-to-actions inside your messages. Must be a 3 or 6-character hexadecimal color.
customText

The list of localizable strings. These strings can be modified. If an option is not given a custom string, the default value will be used.

Option Default value
actionPaymentCompleted Payment Completed
actionPaymentError An error occurred while processing the card. <br> Please try again or use a different card.
actionPostbackError An error occurred while processing your action. Please try again.
clickToRetry Message not delivered. Click to retry.
clickToRetryForm Form not submitted. Click anywhere on the form to retry.
connectNotificationText Sync your conversation and continue messaging us through your favorite app.
connectNotificationSingleText Be notified when you get a reply.
conversationListHeaderText My conversations
conversationListRelativeTimeJustNow Just now
conversationListRelativeTimeMinute 1 minute ago
conversationListRelativeTimeMinutes {value} minutes ago
conversationListRelativeTimeHour 1 hour ago
conversationListRelativeTimeHours {value} hours ago
conversationListRelativeTimeYesterday Yesterday
conversationListTimestampFormat MM/DD/YY
conversationListPreviewAnonymousText Someone
conversationListPreviewCarouselText {user} sent a message
conversationListPreviewFileText {user} sent a file
conversationListPreviewFormText {user} sent a form
conversationListPreviewFormResponseText {user} filled a form
conversationListPreviewImageText {user} sent an image
conversationListPreviewLocationRequestText {user} sent a location request
conversationListPreviewUserText You
conversationTimestampHeaderFormat MMMM D YYYY, h:mm A
couldNotConnect Offline. You will not receive messages.
couldNotConnectRetry Reconnecting...
couldNotConnectRetrySuccess You're back online!
couldNotLoadConversations Couldn’t load conversations.
emailChangeAddress Change my email
emailDescription To be notified by email when you get a reply, enter your email address.
emailFieldLabel Email
emailFieldPlaceholder Your email address
emailFormButton Submit
emailLinkingErrorMessage Please submit a valid email address.
fetchHistory Load more
fetchingHistory Retrieving history...
fileTooLargeError Max file size limit exceeded ({size})
fileTypeError Unsupported file type.
formErrorInvalidEmail Email is invalid
formErrorNoLongerThan Must contain no more than ({characters}) characters
formErrorNoShorterThan Must contain at least ({characters}) characters
formErrorUnknown This doesn't look quite right
formFieldSelectPlaceholderFallback Choose one...
frontendEmailChannelDescription To talk to us using email just send a message to our email address and we'll reply shortly:
headerText How can we help?
imageClickToReload Click to reload image.
imageClickToView Click to view {size} image.
imagePreviewNotAvailable Preview not available.
inputPlaceholder Type a message...
inputPlaceholderBlocked Complete the form above...
introAppText Message us below or from your favorite app.
lineChannelDescription To talk to us using LINE, scan this QR code using the LINE app and send us a message.
linkError An error occurred when attempting to generate a link for this channel. Please try again.
linkChannelPageHeader Sync your conversation
locationNotSupported Your browser does not support location services or it’s been disabled. Please type your location instead.
locationSecurityRestriction This website cannot access your location. Please type your location instead.
locationSendingFailed Could not send location
locationServicesDenied This website cannot access your location. Allow access in your settings or type your location instead.
messageError An error occured while sending your message. Please try again.
messageIndicatorTitlePlural ({count}) New messages
messageIndicatorTitleSingular ({count}) New message
messageRelativeTimeDay {value}d ago
messageRelativeTimeHour {value}h ago
messageRelativeTimeJustNow Just now
messageRelativeTimeMinute {value}m ago
messageTimestampFormat h:mm A
messageDelivered Delivered
messageSeen Seen
messageSending Sending...
messageTooLongError Max message size limit exceeded ({size}).
messengerChannelDescription Connect your Facebook Messenger account to be notified when you get a reply and continue the conversation on Facebook Messenger.
newConversationButtonText New Conversation
notificationSettingsChannelsDescription Sync this conversation by connecting to your favorite messaging app to continue the conversation your way.
notificationSettingsChannelsTitle Other Channels
notificationSettingsConnected Connected
notificationSettingsConnectedAs Connected as {username}
prechatCaptureGreetingText Hi there 👋\nTo start off, we'd like to know a little bit more about you:
prechatCaptureNameLabel Your name
prechatCaptureNamePlaceholder Type your name...
prechatCaptureEmailLabel Email
prechatCaptureEmailPlaceholder name@company.com
prechatCaptureConfirmationText Thanks for that! What can we help you with?
prechatCaptureMailgunLinkingConfirmation You'll be notified here and by email at {email} once we reply.
sendButtonText Send
settingsHeaderText Settings
shareLocation Location
smsBadRequestError We were unable to communicate with this number. Try again or use a different one.
smsCancel Cancel
smsChangeNumber Change my number
smsChannelDescription Connect your SMS number to be notified when you get a reply and continue the conversation over SMS.
smsChannelPendingDescription Check your messages at {number} to confirm your phone number.
smsContinue Send
smsInvalidNumberError Please submit a valid phone number.
smsLinkCancelled Link to {appUserNumber} was cancelled.
smsLinkPending Pending
smsPingChannelError There was an error sending a message to your number.
smsSendText Send me a text
smsStartTexting Start Texting
smsTooManyRequestsError A connection for that number was requested recently. Please try again in {minutes} minutes.
smsTooManyRequestsOneMinuteError A connection for that number was requested recently. Please try again in 1 minute.
smsUnhandledError Something went wrong. Please try again.
syncConversation Sync conversation
tapToRetry Message not delivered. Tap to retry.
tapToRetryForm Form not submitted. Tap anywhere on the form to retry.
telegramChannelDescription Connect your Telegram account to be notified when you get a reply and continue the conversation on Telegram
unsupportedMessageType Unsupported message type.
unsupportedActionType Unsupported action type.
uploadDocument File
uploadInvalidError Invalid file.
uploadPhoto Image
uploadVirusError A virus was detected in your file and it has been rejected
viberChannelDescription Connect your Viber account to be notified when you get a reply and continue the conversation on Viber. To get started, scan the QR code using the Viber app.
viberChannelDescriptionMobile Connect your Viber account to be notified when you get a reply and continue the conversation on Viber. To get started, install the Viber app and tap Connect.
viberQRCodeError An error occurred while fetching your Viber QR code. Please try again.
wechatChannelDescription Connect your WeChat account to be notified when you get a reply and continue the conversation on WeChat. To get started, scan this QR code using the WeChat app.
wechatChannelDescriptionMobile Connect your WeChat account to be notified when you get a reply and continue the conversation on WeChat. To get started, save this QR code image and upload it <a href=\'weixin://dl/scan\'>QR code scanner</a>.
wechatQRCodeError An error occurred while fetching your WeChat QR code. Please try again.
whatsappChannelDescriptionDesktop Sync your account to WhatsApp by scanning the QR code or clicking the link below.\nThen, send the pre-populated message to validate the sync request. (Your code: {{code}}).
whatsappChannelDescriptionMobile Sync your account to WhatsApp by clicking the link below.\nThen, send the pre-populated message to validate the sync request. (Your code: {{code}}).
whatsappLinkingError An error occurred while fetching your WhatsApp linking information. Please try again.

See below for an example.

menuItems
Option Optional? Default value Description
imageUpload Yes true Enables the image upload menu item.
fileUpload Yes true Enables the file upload menu item.
shareLocation Yes true Enables the share location menu item.

See below for an example.

prechatCapture
Option Optional? Default value Description
avatarUrl Yes undefined Sets the URL of the avatar to use for the automatic reply to the prechat capture messages.
enabled Yes false Enables the prechat capture experience.
enableEmailLinking Yes true Automatically links the user's email to the app's Mailgun integration if it exists. If the property fields is defined, the first field of type email will be used.
fields Yes - Overrides the default Prechat Capture fields to define a custom form.

beforeSend delegate will apply to the user's submitted message.

See below for an example.

prechatCapture uses the following customText options:

Option Description
prechatCaptureGreetingText Text for the initial greeting message.
prechatCaptureNameLabel Label displayed for the default form's first field.
prechatCaptureNamePlaceholder Placeholder for the default form's first field.
prechatCaptureEmailLabel Label displayed for the default form's second field.
prechatCaptureEmailPlaceholder Placeholder for the default form's second field.
prechatCaptureConfirmationText Text for the confirmation message sent when the form is completed.
prechatCaptureMailgunLinkingConfirmation Text for the notification message when a user has linked their email address.
Example
var skPromise = Smooch.init({
    integrationId: '<integration-id>',
    // For authenticated mode
    jwt: 'your_jwt',
    externalId: 'user_external_id',
    locale: 'en-US',

    customColors: {
        brandColor: '65758e',
        conversationColor: '65758e',
        actionColor: '65758e',
    },

    menuItems: {
        imageUpload: true,
        fileUpload: true,
        shareLocation: true,
    },

    fixedHeader: false,

    prechatCapture: {
        avatarUrl: 'http://domain.com/images/avatar.png',
        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',
                    },
                ],
            },
        ],
    },

    customText: {
        actionPaymentCompleted: 'Payment Completed',
        actionPaymentError:
            'An error occurred while processing the card. <br> Please try again or use a different card.',
        actionPostbackError: 'An error occurred while processing your action. Please try again.',
        clickToRetry: 'Message not delivered. Click to retry.',
        clickToRetryForm: 'Form not submitted. Click anywhere on the form to retry.',
        connectNotificationText: 'Sync your conversation and continue messaging us through your favorite app.',
        connectNotificationSingleText: 'Be notified when you get a reply.',
        conversationListHeaderText: 'My conversations',
        conversationListPreviewAnonymousText: 'Someone',
        conversationListPreviewCarouselText: '{user} sent a message',
        conversationListPreviewFileText: '{user} sent a file',
        conversationListPreviewFormText: '{user} sent a form',
        conversationListPreviewFormResponseText: '{user} filled a form',
        conversationListPreviewImageText: '{user} sent an image',
        conversationListPreviewLocationRequestText: '{user} sent a location request',
        conversationListPreviewUserText: 'You',
        conversationListRelativeTimeJu