朋友您好我将webview集成在本机app中,下面是我的代码
render() {
const injectedJs = `
var elements = document.querySelectorAll("input[type=submit]");
elements[0].addEventListener("click", function() {
window.postMessage("Button1");
});
elements[1].addEventListener("click", function() {
window.postMessage("Button2");
});
`;
return (
<View style={{ flex: 1 }}>
<WebView
source={{ uri: this.state.authURL }}
bounces={true}
style={{flex: 1}}
injectedJavaScript={injectedJs}
startInLoadingState
scalesPageToFit
javaScriptEnabledAndroid={true}
javaScriptEnabled={true}
onNavigationStateChange={this.handleNavigationStateChange}
onMessage={event => {
console.log("MESSAGE IN ONMESSAGE" + event.nativeEvent.data);
}}
onLoadStart={() => {
console.log("LOAD START ");
}}
onLoadEnd={() => {
console.log('LOAD END');
}}
onError={err => {
console.log('ERROR ');
console.log(err);
}}
/>
</View>
)
}
当我运行上面的代码时,我有一个webview,并且在Button2和Button2之类的两个按钮里面。当我点击Button1时应该在webview中的onMessage事件中打印,但它现在不打印所以任何想法我怎么能解决这个问题?
答案 0 :(得分:0)
如果遇到错误:“在WebView上设置onMessage会覆盖window.postMessage的现有值,但已定义了先前的值。”
然后解决方案是在您的InjectionJs中添加以下代码。
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;