Monday, June 3, 2024
21
rated 0 times [  27] [ 6]  / answers: 1 / hits: 7625  / 3 Years ago, fri, may 7, 2021, 12:00:00

I'm trying to inject JS code to alert the user before the content of the React Native Webview loads, however, for me it just goes to the activity indicator and loads the Webview without injecting any Javascript. How do I fix this? Code below:


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} />;
}

Btw, I am running the app on my iOS device if that helps you to answer.


More From » react-native

 Answers
5

You should include onMessage={(event) => {}} in the WebView


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) => {}}
/>

[#1389] Wednesday, April 28, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jamilab

Total Points: 687
Total Questions: 88
Total Answers: 86

Location: Antigua and Barbuda
Member since Sat, Apr 24, 2021
3 Years ago
jamilab questions
;