[英]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.