[英]Inject Javascript Function not working in Android React Native WebView but work fine in iOS React Native
应用 webview 时我遇到了挑战。 我想将 Javascript 函数注入到我的 webview 中,但它只适用于 iOS 而不适用于 Android。
看看我的代码:
网页浏览:
<WebView
source={{uri:"http://mywebview.com/webview.php"}}
injectedJavaScript={jsCode}
mixedContentMode={'compatibility'}
javaScriptEnabledAndroid={true}
style={{height: 300}} />
要注入的 JSCode:
let jsCode = `function doPopUp() {
document.querySelector('#myBody').style.backgroundColor = 'red';
alert('hello world from webview');
}`;
在 iOS 中它可以正常工作,但在 Android 中则不行。 如果我不注入 JS(我直接将它放在 php 文件中)然后在 Android 浏览器中打开它就可以正常工作。 给您的附加信息是,如果我没有将语法放入 js 函数中,它就可以正常工作。 为什么? 以及如何解决它?
对于 android,在添加 javascript 函数时,我们需要将其添加为 DOM 的一部分。 为此,将function
替换为 jsCode 中的document
。
let jsCode = `docuement.doPopUp() {
document.querySelector('#myBody').style.backgroundColor = 'red';
alert('hello world from webview');
}`;
经过几个小时的尝试,我找到了解决此问题的方法。 像这样的事情会起作用。
没有 ref,由于某种原因,injectedJavaScript 将无法运行。 使用 ref 设置, webViewRef.current.injectJavaScript(runFirstScript);
,injectedJavaScript 也会运行。
这只是 IOS 中的问题,而不是 android 中的问题。
我也将此解决方案发布到了 react-native-webview 的 github 问题。 https://github.com/react-native-webview/react-native-webview/issues/1291
...
const runFirstScript = `
document.body.style.backgroundColor = 'red';
setTimeout(function() { window.alert('hi') }, 2000);
true; // note: this is required, or you'll sometimes get silent failures
`;
webViewRef.current.injectJavaScript(runFirstScript);
return (
<>
<WebView
ref={ref => (webViewRef.current = ref)}
cacheEnabled={true}
// injectedJavaScript={runFirstScript} // other script to run after entire webview has mounted
javaScriptEnabled
mixedContentMode={'compatibility'}
onMessage={event => {
// alert(event.nativeEvent.data);
}}
originWhitelist={['*']}
scalesPageToFit
source={{uri: 'https://example.com'}}
startInLoadingState={true}
userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"
/>
</>
);```
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.