我无法让React Native WebView postMessage正常工作.React本机应用程序成功接收来自web应用程序的post message sendt.但web应用程序不会接收来自React本机应用程序的消息.
My simple web app
<html>
<body>
<button>Send post message from web</button>
<div>Post message log</div>
<textarea style="height: 50%; width: 100%;" readonly></textarea>
<script>
var log = document.querySelector("textarea");
document.querySelector("button").onclick = function() {
console.log("Send post message");
logMessage("Sending post message from web..");
window.postMessage("Post message from web", "*");
}
window.addEventListener("message", function(event) {
console.log("Received post message", event);
logMessage(event.data);
}, false);
function logMessage(message) {
log.append((new Date()) + " " + message + "\n");
}
</script>
</body>
</html>
此web应用的托管时间为:https://popping-heat-6062.firebaseapp.com/
My simple React Native app
import React, {Component} from "react";
import {AppRegistry, Text, View, TouchableHighlight, WebView} from "react-native";
export default class WevViewApp extends Component {
constructor( props ) {
super( props );
this.webView = null;
}
onMessage( event ) {
console.log( "On Message", event.nativeEvent.data );
}
sendPostMessage() {
console.log( "Sending post message" );
this.webView.postMessage( "Post message from react native" );
}
render() {
return (
<View style={{flex: 1}}>
<TouchableHighlight style={{padding: 10, backgroundColor: 'blue', marginTop: 20}} onPress={() => this.sendPostMessage()}>
<Text style={{color: 'white'}}>Send post message from react native</Text>
</TouchableHighlight>
<WebView
style={{flex: 1}}
source={{uri: 'https://popping-heat-6062.firebaseapp.com'}}
ref={( webView ) => this.webView = webView}
onMessage={this.onMessage}
/>
</View>
);
}
}
AppRegistry.registerComponent( 'WevViewApp', () => WevViewApp );
Expected result
- 点击"从网络发送帖子"按钮发送
- 点击"从React Native发送帖子"按钮
Actual result
- Web app successfully向React Native app发送消息,并记录在调试器窗口中
- React Native app unsuccessfully向web app发送消息,但不会在web文本区域打印出来
有人知道为什么web应用程序没有收到这些消息吗?
在Android和iOS上都进行了测试.
相关文件:https://facebook.github.io/react-native/docs/webview.html份
Edit:经历了一种可能指出问题的行为.
当直接在web浏览器中测试"从web发送邮件"按钮时,textarea会记录它已发送的邮件以及收到的自己的邮件.
Thu Dec 15 2016 10:20:34 GMT+0100 (CET) Sending post message from web..
Thu Dec 15 2016 10:20:34 GMT+0100 (CET) Post message from web
当从React原生应用程序在WebView中try 相同操作时,textarea只会打印出来
Thu Dec 15 2016 10:20:34 GMT+0100 (CET) Sending post message from web..
网络视图会劫持窗口吗.postMessage方法并注入自定义方法?
这在documentation篇文章中提到:
设置此属性会将postMessage global注入到
也许这是错误的,这就是问题所在?