Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Webview - injectJavascript not working

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.

like image 371
KLG Avatar asked May 07 '26 04:05

KLG


1 Answers

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) => {}}
/>
like image 109
Mic Fung Avatar answered May 08 '26 18:05

Mic Fung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!