React Native Webview - InjectJavascript 不起作用
2021-05-07
12016
我试图注入 JS 代码以在 React Native Webview 的内容加载之前提醒用户,但是,对我来说,它只会转到活动指示器并加载 Webview,而不会注入任何 Javascript。我该如何解决这个问题?以下代码:
import React from 'react';
import { View, ActivityIndicator } from 'react-native';
import { WebView } from 'react-native-webview';
import styles from '../../styles';
export default function Links() {
function LoadingIndicatorView() {
return (
<View style={styles.hubLoading}>
<ActivityIndicator color='#009b88' size='large' />
</View>
)
}
const runFirst = `
setTimeout(function() { window.alert('hi') }, 2000);
true; // note: this is required, or you'll sometimes get silent failures
`
return <WebView source={{ uri: https://www.google.com/ }} renderLoading={LoadingIndicatorView} startInLoadingState={true} javaScriptEnabled={true} injectedJavaScript={runFirst} />;
}
顺便说一句,我正在我的 iOS 设备上运行该应用程序,如果这有助于您回答。
2个回答
您应该在
WebView
中包含
onMessage={(event) => {}>
https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md
An onMessage event is required as well to inject the JavaScript code into the WebView.
<WebView
source={{ uri: "https://www.google.com/" }}
renderLoading={LoadingIndicatorView}
startInLoadingState={true}
javaScriptEnabled={true}
injectedJavaScript={runFirst}
onMessage={(event) => {}}
/>
Mic Fung
2021-05-07
尝试
injectedJavaScriptBeforeContentLoaded={injectedJavascript}
Danniel Lee
2022-02-22