反应版本:
"react": "16.6.3","react-native": "^0.58.5","react-native-webview": "^5.3.1"
说明:
WebView onMessage在Android上不起作用。甚至没有从本地响应接收数据。
我正在尝试webview.postMessage('') 来自JS。
我已经添加了事件监听器来发布消息 使用window.addEventListener和document.addEventListener。
将数据从Webview发送回React Native 使用window.ReactNativeWebView.postMessage(dataToTransfer)
代码:
export default class TestContainer extends Component {
sendPostMessage = () => setTimeout(() => {
this.webView.postMessage(' loaded')
}, 100)
render() {
return (
<SafeAreaView forceInset={{ top : 'always', bottom : 'always'}} style={{flex:1}}>
<View style={{ width : '100%', height : '100%' }} >
<WebView
javaScriptEnable={true}
onLoadEnd={this.sendPostMessage}
source={{html}}
ref={(component) => (this.webView = component)}
onMessage={this.handleMessage}
injectedJavaScript={" setTimeout(function(){ window.postMessage('asdsa', '*'); },1000); "}
/>
</View>
</SafeAreaView>
)
}
handleMessage = (event) => {
Alert.alert('handle message')
let msgData;
try {
msgData = JSON.parse(event.nativeEvent.data);
console.log('WebViewLeaf : received message: ', msgData)
} catch (err) {
console.log('error',err);
}
}; }
JS代码:
function sendData(){
var text =document.getElementById("text").value;
var dataToTransfer = JSON.stringify({
"description" : 'Return data from webview to react native',
"data" : String(text)
})
window.ReactNativeWebView.postMessage(dataToTransfer)}
function receiveMessage(event){
document.getElementById('demo').innerHTML = JSON.parse(event.data).description}
window.addEventListener("message", receiveMessage, false);
document.addEventListener("message", receiveMessage, false);
HTML代码:
<body> <h1>Enter Text :</h1> <input type="text" id="text" name="text"/><br/> <input type="button" value="send" onclick="sendData()"/> <p id="demo"></p></body>