Skip to content

Instantly share code, notes, and snippets.

@hetmann
Last active December 20, 2023 07:18
Show Gist options
  • Save hetmann/bda29c335da8bb51f8e2e2d520edf3b6 to your computer and use it in GitHub Desktop.
Save hetmann/bda29c335da8bb51f8e2e2d520edf3b6 to your computer and use it in GitHub Desktop.
React Native implementation for Zendesk Chat using WebView & Modal components
import React, { Component } from "react";
import { WebView } from "react-native-webview";
import { Button, Modal, View } from "react-native";
// Author: Hetmann Wilhelm Iohan
// Email: [email protected]
// Web: https://react-ui-kit.com
// YouTube: https://www.youtube.com/react-ui-kit
// This is a basic example showing how to use Zendesk Chat Widget using a webview inside a modal and a html code
// Currently Zendesk Chat SDK doesn't support React-Native so
// this is a standalone example using just a HTML code and JS widget
// How to use
// 1. copy/paste the zendesk_chat_key from resource #3 link
// 2. originWhitelist is set to "about:blank" to open any links outside the WebView Modal
// 3. customize the widget using resource #2 link
// 4. from a web browser and as an agent open resource #1 link to chat with clients from the app
// Resources
// 1. Zendesk Chat Agent url: https://splendchat.zendesk.com/chat/agent
// 2. Zendesk Chat API Key: https://splendchat.zendesk.com/chat/agent?#widget/getting_started
// 3. Zendesk Web Widget: https://developer.zendesk.com/embeddables/docs/widget/core
class ZendeskChat extends Component {
state = {
showChat: false
};
chatHTML() {
const { title, user, zendesk_chat_key } = this.props;
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Chat | ${title}</title>
<!-- Start of Zendesk Widget script -->
<script id="ze-snippet"
src="https://static.zdassets.com/ekr/snippet.js?key=${zendesk_chat_key}"> </script>
<!-- End of Zendesk Widget script -->
<style type="text/css">html { background: #000; }</style>
</head>
<body>
<script>
document.addEventListener( 'DOMContentLoaded', function( event ) {
// zE('webWidget', 'prefill', {
// name: { value: "${user.name}", readOnly: true },
// email: { value: "${user.email}", readOnly: true },
// phone: { value: "${user.phone}", readOnly: true }
// });
// zE('webWidget', 'identify', { name: "${user.name}", email: "${user.email}" });
zE('webWidget', 'open');
zE('webWidget:on', 'close', () => window.ReactNativeWebView.postMessage("close"));
});
</script>
</body>
</html>
`;
}
renderChat() {
const { showChat } = this.state;
const userAgent = "YourApp";
return (
<Modal {...this.props} visible={showChat}>
<WebView
useWebKit
style={{ flex: 1 }}
hideKeyboardAccessoryView
source={{ html: this.chatHTML() }}
showsVerticalScrollIndicator={false}
applicationNameForUserAgent={userAgent}
onMessage={({ nativeEvent }) => {
nativeEvent.data === "close" && this.setState({ showChat: false });
}}
originWhitelist={["about:blank"]}
// shouldStartLoadWithRequestHandler={({ url }) => url.startsWith("about:blank")}
/>
</Modal>
);
}
render() {
return (
<View style={{ flex: 1, justifyContent: "center" }}>
<Button title="Chat with us" color="black" onPress={() => this.setState({ showChat: true })} />
{this.renderChat()}
</View>
);
}
}
ZendeskChat.defaultProps = {
title: "Test",
user: {
name: "React UI Kit",
email: "[email protected]",
phone: "12345678"
},
zendesk_chat_key: ""
// get the key from the code snippet found at:
// https://splendchat.zendesk.com/chat/agent?#widget/getting_started
};
export default ZendeskChat;
@saeedtkh
Copy link

it

@SaeedThk try to follow the comments. Try this ->

I think I already fixed that. I have moved HTML code to separate file and in WebView in source prop I have path to local HTML file. Also I have changed originWhitelist value to [*]. I'm not sure this is fine in 100% but now I see the Chat and I sent message.

It is working like a charm!! Thank you very much!

@hheras
Copy link

hheras commented Apr 21, 2021

For those trying to use the webview with static html (as the original example), add baseurl: "https://static.zdassets.com" prop to the WebView and change originWhitelist to [*], so it would be something like this:

<WebView useWebKit style={{ flex: 1 }} hideKeyboardAccessoryView source={{ html: this.chatHTML(), baseUrl: 'https://static.zdassets.com' }} showsVerticalScrollIndicator={false} applicationNameForUserAgent={userAgent} onMessage={({ nativeEvent }) => { nativeEvent.data === 'close' && this.setState({ showChat: false }); }} originWhitelist={['*']} />

@Burhan-Rashid
Copy link

Burhan-Rashid commented Aug 21, 2021

i copied the same code, but it is not working for me. it shows only black background. I am using expo for react native. Will it work on expo or it works only with bare react native @hetmann

@hetmann
Copy link
Author

hetmann commented Aug 23, 2021

@Burhan-Rashid it should work on expo or react-native. This is kinda old implementation based on their API version at that time.

@BuhorDenysDEV
Copy link

I do step by step, but have see only background color black. Do I smth do wrong? Can @hetmann you help me?
I changed your component to functional. But I think, it's not a problem:


import React, { useState } from "react";
import { WebView } from "react-native-webview";
import { Button, Modal, View } from "react-native";

// Author: Hetmann Wilhelm Iohan
// Email: [email protected]
// Web: https://react-ui-kit.com
// YouTube: https://www.youtube.com/react-ui-kit

// This is a basic example showing how to use Zendesk Chat Widget using a webview inside a modal and a html code
// Currently Zendesk Chat SDK doesn't support React-Native so
// this is a standalone example using just a HTML code and JS widget

// How to use
// 1. copy/paste the zendesk_chat_key from resource #3 link
// 2. originWhitelist is set to "about:blank" to open any links outside the WebView Modal
// 3. customize the widget using resource #2 link
// 4. from a web browser and as an agent open resource #1 link to chat with clients from the app

// Resources
// 1. Zendesk Chat Agent url: https://splendchat.zendesk.com/chat/agent
// 2. Zendesk Chat API Key: https://splendchat.zendesk.com/chat/agent?#widget/getting_started
// 3. Zendesk Web Widget: https://developer.zendesk.com/embeddables/docs/widget/core

const ZendeskChat = ( props ) => {
const [showChat, setShowChat] = useState(false);
const { title, user, zendesk_chat_key } = props;

const chatHTML = () => {
return <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Chat | ${title}</title> <!-- Start of Zendesk Widget script --> <script id="ze-snippet" src="https://static.zdassets.com/ekr/snippet.js?key=${zendesk_chat_key}"> </script> <!-- End of Zendesk Widget script --> <style type="text/css">html { background: #777888; }</style> </head> <body> <script> document.addEventListener( 'DOMContentLoaded', function( event ) { zE('webWidget', 'prefill', { name: { value: "${user.name}", readOnly: true }, email: { value: "${user.email}", readOnly: true }, phone: { value: "${user.phone}", readOnly: true } }); zE('webWidget', 'identify', { name: "${user.name}", email: "${user.email}" }); zE('webWidget', 'open'); zE('webWidget:on', 'close', () => window.ReactNativeWebView.postMessage("close")); }); </script> </body> </html>;
}

const renderChat = () => {
const userAgent = "YourApp";

return (
  <Modal {...props} visible={showChat}>
    <WebView
      useWebKit
      style={{ flex: 1 }}
      hideKeyboardAccessoryView
      source={{ html: chatHTML() }}
      showsVerticalScrollIndicator={false}
      applicationNameForUserAgent={userAgent}
      onMessage={({ nativeEvent }) => {
        nativeEvent.data === "close" && setShowChat(false);
      }}
      originWhitelist={["about:blank"]}
      shouldStartLoadWithRequestHandler={({ url }) => url.startsWith("about:blank")}
    />
  </Modal>
);

}

return (
<View style={{ flex: 1, justifyContent: "center" }}>
<Button title="Help!" color="white" onPress={() => setShowChat(true)} />
{renderChat()}

);

};

export default ZendeskChat;

@hetmann
Copy link
Author

hetmann commented Jan 19, 2022

@BuhorDenysDEV ohh I see, what can you do is create a web html and see it if works. Maybe their widget has changed.

@BuhorDenysDEV
Copy link

@hetmann may be you right.. because, in our project RN 0.65 and all zendesk libs don't work with it. I think smth change )
I will tried your advice and check what wrong.

@BuhorDenysDEV
Copy link

@hetmann your code work! My client give me wrong key 😬... and now - all work!
Thank you, bro!

@hetmann
Copy link
Author

hetmann commented Jan 21, 2022

@robertoyoc
Copy link

Any way to send a RNmessage when chat opens? Basically to show a loading animation while it appears on the screen.

@stri8ed
Copy link

stri8ed commented Jul 28, 2022

For those trying to use the webview with static html (as the original example), add baseurl: "https://static.zdassets.com" prop to the WebView and change originWhitelist to [*], so it would be something like this:

<WebView useWebKit style={{ flex: 1 }} hideKeyboardAccessoryView source={{ html: this.chatHTML(), baseUrl: 'https://static.zdassets.com' }} showsVerticalScrollIndicator={false} applicationNameForUserAgent={userAgent} onMessage={({ nativeEvent }) => { nativeEvent.data === 'close' && this.setState({ showChat: false }); }} originWhitelist={['*']} />

Thanks. The baseurl was required to get it to work on an Expo managed app.

@Bob-MYMC
Copy link

Bob-MYMC commented Aug 4, 2022

The solution worked well for zenDesk messaging, however the event is not fired after the widget is changed to Answer Bot.
Any solutions?

@mmckinley8
Copy link

Does anyone know hot to remove the zendesk logo from the chat room? It's a link, and if you tap on it on mobile, you are then stuck on zendesk's marketing site.

@hetmann
Copy link
Author

hetmann commented Sep 20, 2023

@mmckinley8
Copy link

@mmckinley8 Can you try this package: https://github.com/leegeunhyeok/react-native-zendesk-messaging ?

Thanks for sending this over - as it turns out my firewall was blocking the zendesk widget.

@theewl
Copy link

theewl commented Dec 19, 2023

anyone getting this error when trying to open the chat on the ui?

React Native WebView does not support this platform.

@hetmann
Copy link
Author

hetmann commented Dec 20, 2023

anyone getting this error when trying to open the chat on the ui?

React Native WebView does not support this platform.

Have you tried this package: https://github.com/leegeunhyeok/react-native-zendesk-messaging ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment