3

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.

1
  • Can my answer help you? If yes, please accept the answer. If no, please provide more information for us to help you. Commented May 8, 2021 at 9:01

2 Answers 2

6

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) => {}}
/>
Sign up to request clarification or add additional context in comments.

1 Comment

Hi, how do i pass a value from my react native app to my webview. eg. i have a session id created when i press a button to open the webview, now i need to access that session id inside my webview for configuration.
2

try

injectedJavaScriptBeforeContentLoaded={injectedJavascript}

https://github.com/react-native-webview/react-native-webview/blob/4d8a76f3691479ef22b55e05c07921af99332395/docs/Guide.md#loading-local-html-files

1 Comment

This worked for me. I had onLoad function inside my script

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.