React Native

Updated 

This article walks you through the step-by-step process of integrating Sprinklr Live Chat into your WebView application.

Step 1 - Getting Started​

1. Creating WebView and Adding Live Chat URL  

Before you begin:  
 
WebView URL: http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom

The above URL includes the following parameters:  

  • appId=60c1d169c96beb5bf5a326f3_app_950954: Indicates the Live Chat application ID. To get the app ID, reach out to Sprinklr Support at tickets@sprinklr.com.  

  • device=MOBILE: Indicates that the page is mobile responsive.  

  • enableClose=true: Indicates that a close button has been added to the Live Chat. When the user taps the close button, the onClose SDK callback will be triggered. You will need to set enableClose to true before you try to access it. 

  • zoom=false: Indicates zoom has been disabled inside the WebView.  

Note: To identify the environment where your Sprinklr instance is deployed (for example, prod, prod2, prod4), contact your Success Manager or reach out to Sprinklr Support at tickets@sprinklr.com.

 In your Webview page component, add the following code snippets. 

 

​1. Import WebView from react-native-webview

import { WebView } from 'react-native-webview';const liveChatUrl = 'http://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&webview=true'; // example url, use one provided by sprinklr

2. Render WebView with JS, DomStorage, Cache enabled: 

render() {  return (    <WebView      ref={this.setWebViewRef}      source={{uri: liveChatUrl}}      originWhitelist={originWhiteList} pro     startInLoadingState      javaScriptEnabled      domStorageEnabled      cacheEnabled      onMessage={this.onMessage}      injectedJavaScript={jsChannels}    /> setWebViewRef = webviewRef => {  this.webviewRef = webviewRef; }; 

2. Adding Back Button Handling to Control Hardware Back Button Inside the WebView 

Clicking the back button will take you back to the last page within the Live Chat WebView. 

const goBackJavascript = `(function() {   window.sprChat('goBack', (canGoBack) => {     if(!canGoBack) {       window.ReactNativeWebView.postMessage(JSON.stringify({type: 'closed'}));     }    }); })();`; 

Handle this event in onMessage of WebView. 

onMessage = event => {  const eventData = JSON.parse(event?.nativeEvent?.data);  switch (eventData?.type) {    // ... other cases    case 'closed': {      //Instead of closing the webview, it is recommended to hide webview for best user experience      break;    }    // ... other cases    default:      break; 

Listen to hardware back press on Android: 

componentDidMount = () => {  if (Platform.OS === 'android') {    BackHandler.addEventListener('hardwareBackPress', this.onHandleHardwareBackPress);  componentWillUnmount = () => {  if (Platform.OS === 'android') {    BackHandler.removeEventListener('hardwareBackPress', this.onHandleHardwareBackPress);  onHandleHardwareBackPress = () => {  this.webviewRef?.webviewRef?.injectJavaScript?.(goBackJavascript); 

Note: To provide the best user experience, it is recommended to hide and show the WebView rather than completely destroying it. Additionally, the WebView should be preloaded in the background so that users do not see a loading state when accessing it for the first time.

3. Add Permissions

Android

If you are supporting upload media functionality in messenger, include the following permissions in AndroidManifest.xml:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><uses-permission android:name="android.permission.CAMERA" /><uses-permission android:name="android.permission.RECORD_AUDIO" /><!--   For android 13 and above   --!><uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> <uses-permission android:name="android.permission.READ_MEDIA_VIDEO" /> <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> 

iOS

If you are supporting upload media functionality in messenger, include the following permissions in info.plist file :

<key>NSCameraUsageDescription</key><string>Messenger app requires access to the camera to capture the photos.</string><key>NSMicrophoneUsageDescription</key><string>Messenger app requires access to the microphone to record video.</string><key>NSPhotoLibraryUsageDescription</key><string>Messenger app requires access to the photos library.</string>

4. Initialize Messenger

Live Chat can be initialized for both unauthenticated (anonymous) and authenticated users:

For Anonymous Users

If a user is not logged into your mobile app, you can open live chat without passing user information. The profile created into sprinklr will be an anonymous user.

WebView URL: ​http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom

For Authenticated Users

If a user is already logged into your mobile app, you can pass the authenticated details securely to the chat to authenticate the user on the chat itself. This process is called pre-authentication. In pre-authentication you can pass following information securely from the mobile app to the chat.

You can use two types of WebView URLs:

  • Without Hash Expiry: The hash does not expire.

  • With Hash Expiry: The hash expires after a certain period of time.

WebView URL (Without Hash Expiry)

http://prod-live-chat.sprinklr.com/page?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&user_id=12345&user_firstName=John&user_lastName=Doe&user_profileImageUrl=https://example.com/profilePic.jpg&user_email=John.Doe@example.com&user_phoneNo=9876543210&user_hash=29862e418f58273af0f7fcd0f24652e11ec1ff6c2213b2db7f6e754e59778fc3

URL Parameters:

  • appId, environment and locale are mandatory parameters.

  • user_id=“pass required value”:  Indicates the ID which is passed to profile of user.

  • user_firstName=“pass required value”: Indicates the first name which is passed to profile of user.

  • user_lastName=“pass required value”: Indicates the last name which is passed to profile of user.

  • user_profileImageUrl=“pass required value”: Indicates the profile image which is passed to profile of user.

  • user_email=“pass required value”: Indicates the email ID which is passed to profile of user.

  • user_phoneNo=“pass required value”:  Indicates the phone number which is passed to profile of user.

  • user_hash=“pass required value”:  Indicates the hash generated for profile of user.

Note: If you want to pass more values, use user context, that is, 2. Configuration Step 3.

To know the procedure of how to generate hash, see the How to Generate userHash section below.

WebView URL (With Hash Expiry)

https://live-chat-static.sprinklr.com/test-html/index.html?appId=65a90fd538dc261664c2435e_app_66003823&env=qa6&user_email=John.Doe@gmail.com&user_firstName=John&user_lastName=Doe&user_profileImageUrl=https://example.com/profilePic.jpg&user_phoneNo=9876543210&user_id=12345&user_hash=38a2383cab7249334021910b44a021c3c712e6ba401ecc2ed566c0cc2ba00d58&user_hashCreatedOn=1753948229000

URL Parameters:

  • appId, environment and locale are mandatory parameters.

  • user_id=“pass required value”:  Indicates the ID which is passed to profile of user.

  • user_firstName=“pass required value”: Indicates the first name which is passed to profile of user.

  • user_lastName=“pass required value”: Indicates the last name which is passed to profile of user.

  • user_profileImageUrl=“pass required value”: Indicates the profile image which is passed to profile of user.

  • user_email=“pass required value”: Indicates the email ID which is passed to profile of user.

  • user_phoneNo=“pass required value”:  Indicates the phone number which is passed to profile of user.

  • user_hash=“pass required value”:  Indicates the hash generated for profile of user.

  • user_hashCreatedOn=1753948229000: It indicates the timestamp (in epoch milliseconds) when the hash was generated. The hash will only be valid within the configured expiry window (default: ±1 minute), after which it will be considered invalid.

Note: If you want to pass more values, use user context, that is, 2. Configuration Step 3.

To know the procedure of how to generate hash, see the How to Generate userHash section below.

For Authenticated Custom Users 

This step is done to create a custom user using any custom or specific attributes. In other words, it involves creating user accounts with personalized details or characteristics. 
Below is the example to initiate the process with custom attributes and Hash, where you can  pass the attributes values: 

  • Custom Attribute 1 

  • Custom Attribute 2 

  • Hash 

WebView URL (Without Hash Expiry)

https://prod-live-chat.sprinklr.com/page?appId=6465dce790a15f43312fda6e_app_1702111&device=MOBILE&customUser_tokenA=12345&customUser_tokenB=54321&customUser_hash=4df78ed636fbd333269ebe063f013b47d8ec273f3051f99d4f7645a432f2d326

Note: If you want to implement a Custom User Authentication Flow, contact Sprinklr Support at tickets@sprinklr.com to initiate discussions about the implementation process.

WebView URL (With Hash Expiry)

https://prod-live-chat.sprinklr.com/page?appId=6465dce790a15f43312fda6e_app_1702111&device=MOBILE&customUser_tokenA=12345&customUser_tokenB=54321&customUser_hash=4df78ed636fbd333269ebe063f013b47d8ec273f3051f99d4f7645a432f2d326&customUser_hashCreatedOn=1753948229000

How to Generate userHash?

The userHash is a generated HMAC (Hash-based Message Authentication Code). Sprinklr uses the sha256 hash function for HMAC generation. To create the userHash, you need to generate an HMAC for a concatenated string of user details, with each detail separated by an underscore (_).

You can generate either a userHash without expiry or a userHash that expires after a specified time.

User Details Without Hash Expiry

userId_firstName_lastName_profileImageUrl_phoneNo_email​

Example String (Without Hash Expiry):

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com​

User Details With Hash Expiry

For a userHash with expiry, include an additional timestamp (hashCreatedOn) indicating when the hash was created:

userId_firstName_lastName_profileImageUrl_phoneNo_email_hashCreatedOn

Example String (With Hash Expiry):

12345_John_Doe_https://example.com/profilePic.jpg_9876543210_shane.warne@gmail.com_1753948567000

Sample code for generating the HMAC is available for the following languages:

$key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";$userId = "12345";$firstName = "John";$lastName = "Doe";$profileImageUrl = "https://example.com/profilePic.jpg";$phoneNo = "9876543210";$email = "John.Doe@example.com";$userDetails = $userId."_".$firstName."_".$lastName."_".$profileImageUrl."_".$phoneNo."_".$email;$userHash = hash_hmac('sha256',$userDetails,$key);

Run Online: https://repl.it/@AbhishekPriyam/HMACPHPExample

import hmacimport hashlibuserId = "12345"firstName = "John"lastName = "Doe"profileImageUrl = "https://example.com/profilePic.jpg"phoneNo = "9876543210"email = "John.Doe@example.com"userDetails = userId+"_"+firstName+"_"+lastName+"_"+profileImageUrl+"_"+phoneNo+"_"+emaildef create_sha256_signature(key, data):  byte_key = key.encode()  data= data.encode()  return hmac.new(byte_key, data, hashlib.sha256).hexdigest()userHash=create_sha256_signature("acf32e61-14a6-291b-3a1b-cc8854134ea1", userDetails)

Run Online: https://repl.it/@AbhishekPriyam/HMACPythonExample

require 'openssl'key = 'acf32e61-14a6-291b-3a1b-cc8854134ea1'userId = "12345"firstName = "John"lastName = "Doe"profileImageUrl = "https://example.com/profilePic.jpg"phoneNo = "9876543210"email = "John.Doe@example.com"userDetails = userId+"_"+firstName+"_"+lastName+"_"+profileImageUrl+"_"+phoneNo+"_"+emaildigest = OpenSSL::Digest.new('sha256')userHash = OpenSSL::HMAC.hexdigest(digest, key, userDetails)

Run Online: https://repl.it/@AbhishekPriyam/HMACRubyExample

import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;import java.security.NoSuchAlgorithmException;import java.security.InvalidKeyException;import javax.xml.bind.DatatypeConverter;class Main {public static void main(String[] args) { try {      String key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";      String message = "12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com";       Mac hasher = Mac.getInstance("HmacSHA256");      hasher.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));      byte[] hash = hasher.doFinal(message.getBytes());         System.out.println((DatatypeConverter.printHexBinary(hash)).toLowerCase());   }   catch (NoSuchAlgorithmException e) {}   catch (InvalidKeyException e) {} }}

Run Online: https://repl.it/@AbhishekPriyam/HMACJavaExample

using System;using System.Security.Cryptography;using System.Text; class Program{    static void Main(string[] args)    {        string key = "acf32e61-14a6-291b-3a1b-cc8854134ea1";        string userId = "12345";        string firstName = "John";        string lastName = "Doe";        string profileImageUrl = "https://example.com/profilePic.jpg";        string phoneNo = "9876543210";        string email = "John.Doe@example.com";         string userDetails = $"{userId}_{firstName}_{lastName}_{profileImageUrl}_{phoneNo}_{email}";         using (HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key)))        {            byte[] hashBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(userDetails));            string userHash = BitConverter.ToString(hashBytes).Replace("-", "").ToLower();             Console.WriteLine(userHash);        }    }}

Run Online: https://replit.com/@RoshanDash1/HmacCExample

var crypto = require('crypto');var key = 'acf32e61-14a6-291b-3a1b-cc8854134ea1';var userDetails = '12345_John_Doe_https://example.com/profilePic.jpg_9876543210_John.Doe@example.com';var hash = crypto.createHmac('sha256', key).update(userDetails);hash.digest('hex');

Run Online: https://repl.it/@AbhishekPriyam/HMACNodeExample

Note:

  • firstName, hash and one of email or phoneNumber are mandatory

  • User details are supposed to be concatenated to form a string, separated by underscore as shown below:

userId_firstName_lastName_profileImageUrl_phoneNo_email
  • If you don’t have a few values, you need not send anything but keep the underscores as is. For example, let’s say you don’t have profileimageUrl, there will be 2 underscores after lastName. The string will be as shown below: 

userId_firstName_lastName__phoneNo_email

Step 2 - Configurations

1. Update User

User attributes can be updated by calling, below is the sample configuration example:

const updateUserSettingsJavascript = (payload) => {    const userPayload = JSON.stringify({   user: payload  });  return `window.sprChat('updateUserSettings', ${userPayload});`;   }; const updateUserSettings = () => {   const payload = {             id: id,           firstName: firstName,           lastName: lastName,           profileImageUrl: profileImageUrl,           email: email,           phoneNo: phoneNo,           hash: hash,          hashCreatedOn: (epoch milliseconds) //Add this only if you are using time-based hash expiry }; const javascriptCode = updateUserSettingsJavascript(payload); this.webviewRef?.webviewRef?.injectJavaScript?.(javascriptCode);   }; 

 

Note: firstName, hash and either of email or phone number are mandatory parameters and hash should be generated for every change in user object.

2. Update Custom User 

Custom User attributes can be updated by calling, below is the sample configuration example: 

const updateCustomUserJavascript = (payload) => {    const userPayload = JSON.stringify({     customUser: payload   });   return `window.sprChat('updateUserSettings', ${userPayload});`;   }; const updateUserSettings = () => {   const payload = {       tokenA: tokenA,       tokenB: tokenB,       hash: hash   }; const javascriptCode = updateCustomUserJavascript(payload); this.webviewRef?.webviewRef?.injectJavaScript?.(javascriptCode);    };

3. Update Language

To update the user language use below function:

const updateLocaleJavascript = (locale) => `(function() {       window.sprChat('updatelocale', '${locale}');  })();`;   const updateLocale = () => {      this.webviewRef?.injectJavaScript?.(updateLocaleJavascript('hr'));   

Sprinklr messenger supports the following languages: Arabic, Bokmal, Chinese, English, Thai, Turkish, Vietnamese, Portuguese, Spanish, Indonesian, Japanese, Korean, French. 

Few languages with limited availability are: Albanian, Norwegian, Bosnian, Chinese (traditional), Chinese (honk-kong), Croatian, Czech, Danish, Dutch, Estonian, Finnish, German, Hebrew, Hungarian, Italian, Latvian, Lithuanian, Macedonian, Malayalam, Polish, Romanian, Serbian, Slovak, Slovanian, Swedish.

4. Localization Support  

To achieve localization in Live Chat via WebView approach, you can pass certain “locale” string in query parameters of URL; this will be in addition to ones discussed in Step 1.

URL: https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&locale=en

In the above URL,
locale=en: Indicates the locale which you want to send for this app ID. 

5. Opening Live Chat with Different Landing Screen  

To open Live Chat in different states at different locations, you can pass the relevant string in the query parameters of URL; this will be in addition to ones discussed in Step 1.

Scenario 1: Directly landing on the home screen

URL: https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&locale=en

By default, the Home screen opens.

Scenario 2: Directly landing on the new conversation screen

URL: https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=NEW_CONVERSATION&scope=CONVERSATION

In the above URL:

  • scope=CONVERSATION: Indicates the scope of Live Chat is limited to conversation screen

  • landingScreen=NEW_CONVERSATION: Indicates the landing screen. This opens a new conversation.

Scenario 3: Directly landing on the last conversation screen

URL: https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION

In the above URL:

  • scope=CONVERSATION: Indicates the scope of Live Chat is limited to conversation screen.

  • landingScreen=LAST_CONVERSATION: Indicates the landing screen. This opens the last conversation.

Note: Setting landingScreen to LAST_CONVERSATION allows brands to get users to land the customer on the last interacted open conversation. If there are no open conversations, the customer lands on a new conversation window.

6. Passing Contextual Information of Users to Live Chat from Mobile  

Scenario 1: Capture customer context from the mobile app on all cases of the user

Sometimes you might want to pass some contextual information in case custom fields for all conversations started by the user. (clientContext)

URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION&context_fieldId=value

In the above URL:
context_fieldId="pass required value”: Indicates the context which is passed to all cases of user.

Scenario 2: Update the profile context from mobile app on profile of user 

Sometimes you might want to capture some context on the profile/user during the conversation or after the conversation. (userContext)

URL - https://prod-live-chat.sprinklr.com/page?appId=60c1d169c96beb5bf5a326f3_app_950954&device=MOBILE&enableClose=true&zoom=false&landingScreen=LAST_CONVERSATION&scope=CONVERSATION&userContext_fieldId=value


In the above URL:

userContext_fieldId=“pass required value”:  Indicates the context which is passed to profile of user.

7. Update Conversation Context (Case Custom Field) on Demand 

At times you might want to update the value of conversation context/case custom field during or after a conversation. 

Example: After a purchase is made on the website you might want to set the transaction amount or id on the case for reporting. After doing this, you can attribute sales to each conversation/case. 

To do this:

  1. Create the case custom fields and note down their field name1. 

  2. Whenever you want to update the case custom field, call the following JavaScript function (5e291d040844e435b is the custom field name). 

const updateConversationContextJavascript = () => {   const payload = JSON.stringify({       context: {         "5e291d040844e435b": ["450.32"]       }  });   return `(function() {        window.sprChat('updateConversationContext', ${payload});     })();`;};  const updateConversationContext = () => {  this.webviewRef?.injectJavaScript?.(updateConversationContextJavascript());   

8. Update Profile Context within Profile Custom Fields 

When chat is being opened from a custom button or hyperlink, sometimes you might want to capture some context on the profile/user during the conversation or after the conversation.

To do this:

  1. Create the profile custom fields and note down their field name. 

  2. Whenever you want to update the profile custom field, call the following JavaScript function and pass the information for profile level custom fields. This can be done via sdk for updating it on-demand.

const updateUserContextJavascript = () => {   const payload = JSON.stringify({     "_c_5e291d040844e435b": ["450.32"]   });   return `(function() {        window.sprChat('updateUserContext', ${payload});     })();`;}; const updateUserContext = () => {      this.webviewRef?.injectJavaScript?.(updateUserContextJavascript());   

9. Blocking URLs That Do Not Contain the Live Chat Domain and Opening Them in an External Browser 

Add WebView client to your WebView and override shouldOverrideUrlLoading to block all URLs that do not contain Live Chat domain, inside the onCreate method.  

const originWhiteList = ['https://prod-live-chat.sprinklr.com', 'https://live-chat-static.sprinklr.com']; 

10. Listening to WebView Events 

In this snippet, the JavaScript code sends messages to React Native whenever an event occurs inside the WebView. For each event, it uses window.ReactNativeWebView.postMessage() to pass relevant data back to the React Native app.

onMessage = event =>   const eventData = JSON.parse(event?.nativeEvent?.data);  switch (eventData?.type) {    case 'loadError': {      // You can show some ui error      break;    }    case 'onLoad': {      // You can call your js methods after that      break;    }    case 'onClose': {      // Instead of closing the webview, it is recommended to hide webview for best user  experience      break;    }    case 'onUnreadCountChange': {      const {params} = eventData;      // You can show the notification count using this      break;    }    case 'onExternalEvent': {      const {params} = eventData;      // Handle the event here      break;    }    default:      break; 

Adding JavaScript channels to your WebView: 

 

Injecting Javascript 

const jsChannels = `(function () {  window.sprChat('onLoad', (error) => {    if (error) {      window.ReactNativeWebView.postMessage(JSON.stringify({type: 'loadError'}));    } else {       window.ReactNativeWebView.postMessage(JSON.stringify({type: 'onLoad'}));    }  });  window.sprChat('onClose', ()  => {    window.ReactNativeWebView.postMessage(JSON.stringify({type: 'closed'}));  });  window.sprChat('onUnreadCountChange', (params) => {    window.ReactNativeWebView.postMessage(JSON.stringify({type: 'onUnreadCountChange', params}));  });  window.sprChat('onExternalEvent', (params) => {    window.ReactNativeWebView.postMessage(JSON.stringify({type: 'onExternalEvent', params}));  }); })();`; 

11. Disable Attachments for Customer

You can prevent customers from adding attachments in the chat by hiding the attachment icon from the chat widget.


To do this, you can pass disableAttachment=true in the WebView URL.

URL: https://live-chat-static.sprinklr.com/chat/page/lqRt9K-W6/index.html?appId=65afb12b62317d2d4a58bfad_app_1866548&device=MOBILE&enableClose=true&zoom&disableAttachment=true

12. Update Theme Mode for User on Demand

You can update the theme mode ondemand:

const updateThemeModeJavascript = (mode) => `(function() {        window.sprChat('updateThemeMode', '${mode}');   })();`;    const updateThemeMode = () => {       this.webviewRef?.injectJavaScript?.(updateThemeModeJavascript('DARK'));    

Note: Upon invoking the updateThemeMode() method, a confirmation alert will prompt the user to reload the app for the changes in theme to take effect. Furthermore, the parent application should send the updated theme within the configuration while chat initialization.

13. Configure Your Status Card

Note: To enable this capability, contact Sprinklr Support at tickets@sprinklr.com and provide your Live Chat application ID. The Status Card feature can only be enabled if you are using the modern skin version of the Live Chat widget.

Using status cards, you can update your customers about the health of a key resource. This key resource could be a tool or service that they interact with frequently. By showing the status of this resource directly, customers don’t have to reach to agents repeatedly. Hence, this improves the customer experience while reducing agent workload.

Once status card is enabled for your Live Chat widget, you can update the status card by using the following:

const updateWidgetJavascript = (payload) => {   const stringifiedPayload = JSON.stringify(payload);   return `(function() {        window.sprChat('updateWidget', ${stringifiedPayload});     })();`;}; const 'updateWidget' = () => {   const payload = {         id: 'status_card_1',         details: {             title: 'Status: %%[status]',             description: 'Updated At %%[updatedAt]',             status: 'SERVICE_UNDER_MAINTENANCE',             updatedAt: 1668161693545,             langVsTranslatedFieldValues: {                 'ar': {                     title: '%%[status] : حالة ',                     description: ' %%[updatedAt] : تم التحديث في'                 },                 'es': {                     title: 'Estado : %%[status]',                     description: 'Actualizado en: %%[updatedAt]'                 }} } };     this.webviewRef?.injectJavaScript?.(updateWidgetJavascript(payload));    

You can use the following placeholders for title and description:

  1. %%[updatedAt] --> Placeholder for formatted time

  2. %%[status] --> Placeholder for Status, mentioned below in the table as SPRStatus


Status Placeholder Value


Icon



SPRStatus



All Systems Operational





ALL_SYSTEMS_OPERATIONAL



Service Under Maintenance





SERVICE_UNDER_MAINTENANCE



Partially Degraded Service





PARTIALLY_DEGRADED_SERVICE



Degraded System Service





DEGRADED_SYSTEM_SERVICE



Partial System Outage





MINOR_SYSTEM_OUTAGE



Minor System Outage





PARTIAL_SYSTEM_OUTAGE



Major System Outage





MAJOR_SYSTEM_OUTAGE


14. Add Support to Download Attachment

When a user taps the Download button in Live Chat, they are redirected to a URL which contains the fileUrl and fileName parameters.

The URL can have the following formats:

  • “livechat-app:url=${fileUrl}?fileName=${fileName}”: When there are no query parameters present in the fileUrl, fileName is added as a new query parameter.

  • “livechat-app:url=${fileUrl}&fileName=${fileName}”: When there are query parameters present in the fileUrl already, fileName is added as an extra query parameter. 

 

You need to intercept the requests that have URLs starting with the livechat-app: prefix and parse these URLs to properly download the attachment. The steps to parse are: 

  1. Remove the livechat-app:url= prefix. 

  2. From the remaining URL, extract and remove the fileName query parameter. Use its value to name your file. 

  3. Use the remaining URL to fetch and download content. 

Note: While extracting the fileURL, remove the fileName query parameter from the original query. If it’s not removed, a signature mismatch may occur, resulting in a SignatureDoesNotMatch or BlobNotFound error.

For example, when receiving a URL like “livechat-app:url= https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ&fileName=sample_name.pdf”, follow these steps.

 

  1. Remove the prefix to get “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ& fileName=sample_name.pdf”  

  2. Extract the fileName query parameter and name the file sample_name.pdf

  3. Use the remaining URL “https://prod-sprcdn-assets.sprinklr.com/1234/sample.pdf?signature=XYZ” to download the file. 

Step 3 - Push Notifications

For more information on mobile push notifications, refer to Push Notifications in Mobile.

Prerequisite

  • Android: Google service.json file

  • iOS: APNS certificate (P12) along with its credentials

Note: Consider the following points:

  • Google service.json file can be different for staging/prod env

  • APNS certificate (P12) and its credentials must be different for staging/prod env

  • If you are testing the push notification setup on prod mobile application(iOS), ensure to use test flight build

  • If the Google service.json file is different for sandbox/prod env and you are testing the push notification setup on prod mobile application(Android), ensure to use test flight build

Configuration

To enable push notifications, raise a support ticket to tickets@sprinklr.com with the following information:

  • Google service.json file

  • APNS certificate (P12) along with its credentials

  • Live Chat AppID

  • Partner ID

  • Env

 

1) Register for Push Notifications  

You can register the messenger for sending push notifications by providing push token received from fcm as below: 

Note: Registration must only be initiated after the load is complete. 

Create a function in the following way and pass token, deviceId and deviceName as arguments to it to register your device for push notification. 

function getTokenRegistrationJSChannel(token, deviceId, deviceName) {  const payload = {    deviceId,    deviceToken: token,    appVersion: 1, // App version should be a numeric value    deviceName,    mobileClientType: 'ANDROID', //ANDROID | IPHONE  const stringifiedPayload = JSON.stringify(payload);  return `(function() {    window.sprChat('registerDevice', ${ stringifiedPayload });  })();`; 

registerPushNotifications = () => {  this.webviewRef?.webviewRef?.injectJavaScript?.(getTokenRegistrationJSChannel('1234', '123', 'android_device')); 

 

2) Unregister for Push Notifications

To stop receiving notifications, deregister your device as shown below:

 

function getTokenUnRegistrationJSChannel(token, deviceId, deviceName) {  const payload = {    deviceId,    deviceToken: token,    appVersion: 1, // App version should be a numeric value    deviceName,    mobileClientType: 'ANDROID', //ANDROID | IPHONE  const stringifiedPayload = JSON.stringify(payload);  return `(function() {    window.sprChat(''unregisterDevice'', ${ stringifiedPayload });  })();`; 

unRegisterPushNotifications = () => {  this.webviewRef?.webviewRef?.injectJavaScript?.(getTokenUnRegistrationJSChannel('dDf1pGAURse00yE63B4h-c:APA91bHQGe-QlDh6xn7R72ewdfxMQSrnZpVR_Gr9galdGYnGBOU6CbKrUOMJeoUcwmZxpas6lm90RJoKjUEDYz1BJmPpcMY1N_67rou2w0tIFBznKY4Nup7NG9CYR1BKRWGR58c4fCgt', '60cc78666ed3d036e761d962', 'PIXEL_XL')); 

 

3) Handle Messenger Push Notifications 

Once you have registered for messenger push notifications then you might receive notifications from your platform as well as messenger. To check if notification is messenger notification you can check as below: 

Note: When the user is on the Live Chat app, they will always receive the Live Chat messenger push notifications. However, you can define whether users should receive the messenger notifications when they are on the brand app and not the Live Chat app. That is, the brand app is in the foreground and the Live Chat app is running in the background.

To do that, you can check whether the notification is a Live Chat notification and handle it according to brand requirements. For example, you can choose not to display Live Chat notifications when the user is on the brand app.

const et = notification?.et ?? ''; const isMessengerNotification = et === 'LIVE_CHAT_MOBILE_NOTIFICATION';  if (isMessengerNotification) {  handleNotification(notification); 

Once you have identified if the notification is messenger notification you need open the messenger and call handle notification method as described below: 

handleNotification = notification => {  const stringifiedPayload = JSON.stringify(notification);  const sdkFunction = `(function() {    window.sprChat('onNotification',${  stringifiedPayload  });  })();`  this.webviewRef?.webviewRef?.injectJavaScript?.(sdkFunction); 

Troubleshooting

This section lists the common issues and their resolutions:

Issue 1: Sprinklr webview URL is not working

  1. Check if the network connection is properly established. To verify, try loading google.com within your WebView.

  2. Check whitelisting is done properly in the Live Chat builder in Sprinklr platform.

    Steps: Sprinklr Service → Live Chat Care → “ three dots” next to your Live chat Application → Edit → Application Configuration Screen

  3. Check if the example URLs are loading like https://prod0-live-chat.sprinklr.com/page?appId=app_1000073145

Issue 2: Live Chat Not Showing Up When Passing Authenticated User Details

Check the expected hash for any authenticated user passed inside chat settings.

1. Hover over the Options icon alongside your Live Chat Application and select Validate User Hash.

​2. On the Validate User Hash window, enter User ID, Profile Image URL, First Name, Last Name, Phone Number and Email. Click Copy Generated Hash and verify it with the hash generated by you.

Issue 3: Reply Box Not Showing with Keypad

  1. Check and add this configuration in AndroidManifest.xml android:windowSoftInputMode="adjustResize"

  2. Refer here for more details: https://developer.android.com/develop/ui/views/touch-and-input/keyboard-input/visibility#Respond

Issue 4: No Sound During Audio/Video Calls

If you are unable to hear any sound in an audio/video call, make sure that you have added the following configuration to the WebView:

<WebView {...props} mediaPlaybackRequiresUserAction={false} />