I want to get the user's input from a inputfield in webview and then use it in react native to change the value of "answer".
Within webview I created an inputfield with the id="data_1". I get the input data through "oninput" and save it in "answer". But I fail to "answer" into react native by using window.ReactNativeWebView.postMessage(answer);
Any ideas?
This is my code:
import { Button, StyleSheet, Text, View, TouchableOpacity } from "react-native";
import { WebView } from "react-native-webview";
class MySweetComponent extends Component {
render() {
const run = `
document.body.style.backgroundColor = 'blue';
true;`
let answer = "I want to change after user Input"
setTimeout(() => {
this.webref.injectJavaScript(run);
}, 1000);
return (
<View style={{ width: 350, height: 200 }}>
<WebView
scalesPageToFit={false}
ref={(r) => (this.webref = r)}
androidHardwareAccelerationDisabled={true} // To prevent crash when opening screen
onMessage={(event) => {
event.nativeEvent.data;
}}
source={{
html: `
<html>
</pre>
<input type="text" placeholder="Enter text" id="data_1" oninput="getValue()">
<script>
function getValue() {
let answer = document.getElementById("data_1").value;
}
window.ReactNativeWebView.postMessage(answer);
true;
</script>
</body>
</html>
`,
}}
/>
<Text>{answer}</Text>
</View>
);
}
}
export default MySweetComponent;
CodePudding user response:
I think you have an html error with the pre tag
</pre>
just remove that and put your whole <script/>
before the html to be able to call it then.
And might you just want the value once the user ends writing. I would use onblur instead of oninput to avoid sending message for each key pressed, but both ways should work
CodePudding user response:
ok, I think we many things, lets do it step by step
import { useState } from 'react';
import { Button, StyleSheet, Text, View, TouchableOpacity } from "react-native";
import { WebView } from "react-native-webview";
const html = `
<html>
<head></head>
<body>
<input id="myId" placeholder="Enter text" oninput="getValue()">
<script>
window.id = setInterval(() => {
if (window.ReactNativeWebView) {
document.body.style.backgroundColor = 'green';
clearInterval(window.id);
}
}, 1000);
function getValue() {
let answer = document.getElementById("myId").value;
window.ReactNativeWebView.postMessage(answer);
};
</script>
</body>
</html>
`;
const MySweetComponent = () => {
const [answer, setAnswer] = useState("I want to change after user Input");
return (
<View style={{ width: 350, height: 200 }}>
<WebView
onMessage={(event) => {
console.log("EVENT-DATA:", event);
setAnswer(event.nativeEvent.data);
}}
source={{html}}
/>
<Text>{answer}</Text>
</View>
);
};
export default MySweetComponent;