UNPKG

smooch

Version:

Smooch.io powered web messaging

258 lines (214 loc) 104 kB
# [Smooch Web Messenger](https://smooch.io) [![npm version](https://badge.fury.io/js/smooch.svg)](http://badge.fury.io/js/smooch) 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](https://smooch.io/live-web-chat/) 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](https://smooch.io/cross-channel-messaging/) 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](https://smooch.io/rich-messaging/). - Maximize development productivity with a single codebase across platforms and [add more channels](https://smooch.io/cross-channel-messaging/) anytime. - Bring every conversation into your existing business systems. No new tool to learn. [See all integrations](https://smooch.io/integrations/). - Allow [multiple users to participate in a conversation](https://docs.smooch.io/guide/multi-party-conversations/) 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](https://github.com/zendesk/sunshine-conversations-web/releases/tag/5.0.0). ## 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. <!-- prettier-ignore --> ```html <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. ```html <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 ```javascript import Smooch from '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. ## Region configuration Web messenger is supported in the following [regions](https://docs.smooch.io/guide/regions/): | Region | Region identifier | | -------------- | ------------------- | | United States | _Leave unspecified_ | | European Union | `eu-1` | To target the EU region, the region identifier is passed to `Smooch.init()`: ```javascript <script> Smooch.init({ integrationId: '<integration-id>', region: 'eu-1' }).then( function() { // Your code after init is complete }, function(err) { // Something went wrong during initialization } ); </script> ``` If you are a licensed Zendesk customer, use `configBaseUrl` instead of `region`. `configBaseUrl` specifies the URL where the config request is sent. For example: ```javascript <script> Smooch.init({ integrationId: '<integration-id>', configBaseUrl: 'https://<subdomain>.zendesk.com/sc/' }).then( function() { // Your code after init is complete }, function(err) { // Something went wrong during initialization } ); </script> ``` ## 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](#authenticating-the-user-init-vs-login)) | | jwt | Yes | - | Optional. User's authentication token, which can be passed in `init()` as an alternative to `login()` (see [below](#authenticating-the-user-init-vs-login)) | | authCode | Yes | - | An auth code for linking to an existing conversation (see more details [here](https://docs.smooch.io/rest/#get-auth-code)) | | locale | Yes | `en-US` | Locale used for date formatting using the `<language>-<COUNTRY>` format. Language codes can be found [here](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) and country codes [here](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). <br /> **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`. <br /> **Note 2:** this is _only_ used for date formatting and doesn't provide built-in translations for Web Messenger. Refer to the [documentation](https://docs.smooch.io/guide/web-messenger/#strings-customization) 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.](#customcolors) | 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.](#menuitems) | 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](https://docs.smooch.io/guide/web-messenger/#browser-storage) | | delegate | Yes | `undefined` | Sets a delegate on the conversation. See the [delegate](#delegate) section for more details. | | prechatCapture | Yes | [See below.](#prechatcapture) | 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._ Please note that all error messages are prefixed with `errorPrefix` (default: `Error:`). For example, if you set `actionPaymentError` to `An error occurred while processing the card.`, the message shown to the user will be `Error: An error occurred while processing the card.` If you want to remove the prefix, set `errorPrefix` to an empty string. | Option | Default value | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | actionPaymentCompleted | Payment Completed | | actionPaymentError | {errorPrefix} An error occurred while processing the card. `<br>` Please try again or use a different card. | | actionPostbackError | {errorPrefix} 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 | {errorPrefix} Please submit a valid email address. | | errorPrefix | Error: | | fetchHistory | Load more | | fetchingHistory | Retrieving history... | | fileTooLargeError | {errorPrefix} Max file size limit exceeded ({size}) | | fileTypeError | {errorPrefix} Unsupported file type. | | formErrorEntryRequired | {errorPrefix} This entry is required | | formErrorInvalidEmail | {errorPrefix} Email is invalid | | formErrorNoLongerThan | {errorPrefix} Must contain no more than ({characters}) characters | | formErrorNoShorterThan | {errorPrefix} Must contain at least ({characters}) characters | | formErrorUnknown | {errorPrefix} 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 | {errorPrefix} 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 | {errorPrefix} Could not send location | | locationServicesDenied | {errorPrefix} This website cannot access your location. Allow access in your settings or type your location instead. | | messageError | {errorPrefix} 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 | {errorPrefix} 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\