Last active
September 29, 2020 11:21
-
-
Save arjan/1dec8fa48fdc042689a9c66edb4b5aed to your computer and use it in GitHub Desktop.
Botsquad webview react native demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useRef } from "react"; | |
import { Button, StyleSheet, View } from "react-native"; | |
import { WebView } from "react-native-webview"; | |
const userId = "myuserid"; | |
const botHost = "robin.staging.bsqd.me"; | |
export default function App() { | |
const webviewRef = useRef(); | |
function sendMessage(message) { | |
message = message.replace("'", "\\'"); // javascript injectie voorkomen... | |
webviewRef.current.injectJavaScript(`ChatScreen.sendMessage('${message}')`); | |
} | |
function resetConversation() { | |
// het geheime bericht ".stop" sturen zorgt ervoor dat je met een schone lei begint na reload | |
sendMessage(".stop"); | |
// laad de webview opnieuw | |
webviewRef.current.reload(); | |
} | |
function onMessage(m) { | |
let event; | |
try { | |
event = JSON.parse(m.nativeEvent.data); | |
} catch (e) { | |
return; | |
} | |
// console.log("Got chat event:", event); | |
// Doe hier iets met event | |
if (event.type === "text") { | |
// text to speech hier | |
console.log("TTS: " + event.payload.message); | |
} | |
} | |
return ( | |
<View style={styles.container}> | |
<WebView | |
style={{ flex: 1 }} | |
source={{ uri: `https://${botHost}/embed` }} | |
ref={webviewRef} | |
onLoadEnd={() => { | |
setTimeout(() => { | |
webviewRef.current.injectJavaScript(` | |
const events = ChatScreen.eventDispatcher() | |
events.removeAllListeners("chat_event") | |
events.addListener("chat_event", e => window.ReactNativeWebView.postMessage(JSON.stringify(e))) | |
`); | |
}, 500); | |
}} | |
onMessage={onMessage} | |
/> | |
<Button | |
onPress={() => sendMessage("Hallo daar")} | |
title="Send a message" | |
color="#841584" | |
/> | |
<Button | |
onPress={resetConversation} | |
title="New conversation" | |
color="#ff9900" | |
/> | |
</View> | |
); | |
} | |
const styles = StyleSheet.create({ | |
container: { | |
flex: 1, | |
backgroundColor: "#f0f0f0", | |
alignItems: "stretch", | |
justifyContent: "center", | |
}, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment