反应本机版本:0.60
使用的库:react-native-webview(版本:9.0.1)
问题:
当我将我的本机事件处理程序中的postMessage(this.webView.postMessage('somedata')
)发送到Webview时,不会触发onMessage。但是onMessage确实会在Web视图发送的事件上触发。
尝试过的解决方案:
添加了document.eventListener和window.eventListener。当我从react-native发布消息时,仍然不会触发onMessage。
任何帮助将不胜感激。
代码:
// On Click, the following function will run
_sendPostMessage = () => {
//data sent to webview
this.webView.postMessage("getAuthToken");
}
// Inside render() function
<WebView
ref={(webView) => this.webView = webView}
style={styles.webView}
source={{ uri: event.ticket_form_url, headers: headers }}
injectedJavaScript={jsCode}
onMessage={this.onMessage}
renderLoading={this._renderActivityIndicator}
startInLoadingState={true}
/>
// Injected javscript code below
var jsCode = `
(function() {
window.postMessage = function(data) {
window.ReactNativeWebView.postMessage(data);
};
})()
(function() {
var originalPostMessage = window.postMessage;
var patchedPostMessage = function(message, targetOrigin, transfer) {
originalPostMessage(message, targetOrigin, transfer);
};
patchedPostMessage.toString = function() {
return String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage');
};
window.postMessage = patchedPostMessage;
})();
window.addEventListener("message", function(event) {
var uat = ''
if (window.userAuthenticationToken) {
uat = window.userAuthenticationToken()
}
window.postMessage('setAuthToken,' + uat)
});
document.addEventListener("message", function(event) {
var uat = ''
if (window.userAuthenticationToken) {
uat = window.userAuthenticationToken()
}
window.postMessage('setAuthToken,' + uat)
});
`;
// onMessage
onMessage = (event) => {
//data received from webview
console.log('Reached onMessage', event.nativeEvent.data);
var response = event.nativeEvent.data
var data = response.split(',')
}
答案 0 :(得分:0)
您好,您必须使用帖子消息作为InjectionJavascript。例如,
finally
您可以将此包用于webview,以获取美丽的UI。 https://github.com/ilkerkesici/react-native-beauty-webview