首页 > 解决方案 > react-native-webview this.webView.postMessage 不起作用

问题描述

以前的版本不工作,因为它是新的。

"react-native-webview": "^9.0.2" "react-native": "0.62.0",

2. webview options
javaScriptEnabled={true}
mediaPlaybackRequiresUserAction={false}
startInLoadingState={true}
allowUniversalAccessFromFileURLs={true}
onMessage={this.respondToOnMessage}

3. react-native code
this.webView.postMessage( "Post message from react native" );

4. web code

function receiveMessage(e) {
    callbackFunction(JSON.parse(e.data));
}
function RNPostMessage(data) {
    window.ReactNativeWebView.postMessage(data);
}
window.addEventListener('message', receiveMessage, true);

5. react-native error msg
D:\dev\projects\mobile-app\react-native\yc_attend\node_modules\react-devtools-core\dist\backend.js:32 Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'postMessage' of undefined
TypeError: Cannot read property 'postMessage' of undefined

我想知道这个问题的解决方案...

标签: javascriptreact-nativereact-native-webview

解决方案


你必须尝试做injectJavascript而不是this.webview.postMessage()。我以前也这样做过,并且可以在 webview 中获取我的数据。尝试在 react-native 的注入 Javascript 中使用 window.postMessage。react-native-webview 中有用于注入 javascript 的道具。


推荐阅读