QUI*_*PPY 8 html javascript webview react-native
我正在尝试使用onMessage监听器.该网站正在执行postMessage(window.postMessage("Post message from web");)但反应原生的webview onMessage监听器没有做任何事情!我不知道我做错了什么.
这是HTML
<script type="text/javascript">
window.postMessage("Post message from web");
</script>
Run Code Online (Sandbox Code Playgroud)
这是反应原生代码:
<WebView
ref={( webView ) => this.webView = webView}
onMessage={this.onMessage}
source={{uri: 'https://app.sodge.co/login/response.html'}}
/>
Run Code Online (Sandbox Code Playgroud)
onMessage反应原生函数:
onMessage( event ) {
Alert.alert(
'On Message',
event.nativeEvent.data,
[
{text: 'OK'},
],
{ cancelable: true }
)
}
Run Code Online (Sandbox Code Playgroud)
这里也是一个世博小吃......我不知道我做错了(:... https://snack.expo.io/S17AQqWbf
col*_*ick 14
对于仍然对此感到困惑的任何人......这是因为 React Native 和 Webview 之间的通信已被完全重写。是的,window.postMessage(data, *) 已更改为 window.ReactNativeWebView.postMessage(data),但要具体回答这个问题,解决方案,即您需要从 Web 视图支持 window.postMessage 的内容是每个https://github.com/react-native-community/react-native-webview/releases/tag/v5.0.0传递以下道具:
const injectedJavascript = `(function() {
window.postMessage = function(data) {
window.ReactNativeWebView.postMessage(data);
};
})()`
<WebView
injectedJavaScript={injectedJavascript}
ref={( webView ) => this.webView = webView}
onMessage={this.onMessage}
source={{uri: 'https://app.sodge.co/login/response.html'}}
/>Run Code Online (Sandbox Code Playgroud)
然后你可以像往常一样在你的脚本标签(或其他任何地方)中调用 window.postMessage("Post message from web", "*") 。
更新:上述答案仅支持 Android 上 window.postMessage 的旧功能 - 文档中未提及的内容。对于 iOS,只需使用库https://github.com/CharlesStover/react-native-web-view 即可。像往常一样包含 web 视图 - 没有注入的 javascript。iOS 不支持在原生和 webview 之间发送消息或注入 javascript。有关更多信息并了解解决此问题的技巧,请查看https://medium.com/@Charles_Stover/fixing-react-native-webviews-postmessage-for-ios-10e2320b2f14。
Dav*_*ing 12
根据这个问题,你需要等到React Native postMessage替换了本机window.postMessage(不要问我为什么他们要替换原生函数而不是创建一个新函数).
一种解决方案是执行以下操作:
function waitForBridge() {
//the react native postMessage has only 1 parameter
//while the default one has 2, so check the signature
//of the function
if (window.postMessage.length !== 1){
setTimeout(waitForBridge, 200);
}
else {
window.postMessage('abc');
}
}
window.onload = waitForBridge;
Run Code Online (Sandbox Code Playgroud)
如果您像我一样使用react-native-webview后v5.0.0,请使用window.ReactNativeWebView.postMessage(data)!
window.postMessage(data, *) 已更改为
window.ReactNativeWebView.postMessage(data)
https://github.com/react-native-community/react-native-webview/releases/tag/v5.0.0
| 归档时间: |
|
| 查看次数: |
4722 次 |
| 最近记录: |