我在 S3 上托管了一个静态站点,上面有 CloudFront 发行版。
<WebView
ref={webViewRef}
scrollEnabled={false}
source={{ uri: Config.REMOTE_URL }} // CloudFront URL
sharedCookiesEnabled={true}
onMessage={(event) => receivedMessageFromWebView(event.nativeEvent.data)}
/>
我们postMessage()
上网的方式是这样的
const sendDataToWebView = (dataMap: any) => {
const dataToPost = { type: 'data', data: dataMap };
const postMessageJSCode = `
window.postMessage(${JSON.stringify(dataToPost)}, "*");
true;
`;
if (webViewRef && webViewRef.current) {
webViewRef.current.injectJavaScript(postMessageJSCode);
}
}
onMessage
实现如下
const receivedMessageFromWebView = (msgData: any) => {
console.log('Data Received from WebView -->', msgData); // <-- Not working
};
我在这里遗漏了什么?
答案 0 :(得分:0)
与其window.postMessage
不如尝试window.ReactNativeWebView.postMessage
https://github.com/react-native-webview/react-native-webview/blob/master/docs/Reference.md#onmessage
或者文档已经是本地和 webview 之间通信的真正细节:https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native