React Native Webview-injectJavascript不起作用



我试图在加载React Native Webview的内容之前注入JS代码来提醒用户,但对我来说,它只是转到活动指示器并加载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设备上运行这个应用程序,如果这能帮助你回答的话。

您应该在WebView中包含onMessage={(event) => {}}

https://github.com/react-native-webview/react-native-webview/blob/master/docs/Guide.md

还需要onMessage事件将JavaScript代码注入WebView。

<WebView 
source={{ uri: "https://www.google.com/" }}
renderLoading={LoadingIndicatorView}
startInLoadingState={true}
javaScriptEnabled={true}
injectedJavaScript={runFirst}
onMessage={(event) => {}}
/>

尝试

injectedJavaScriptBeforeContentLoaded={injectedJavascript}

https://github.com/react-native-webview/react-native-webview/blob/4d8a76f3691479ef22b55e05c07921af99332395/docs/Guide.md#loading-本地html文件

相关内容

最新更新