Try to inject js like this way:

   const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`;
    return (
      <View style={styles.container}>
        <WebView
          ref={ref => {
            this.webview = ref;
          }}
          source={{ uri: this.state.webViewUrl }}
          originWhitelist={['*']}
          injectedJavaScript={jsCode}
        />
      </View>
    );
  }

for more options take a look: Medium: Injecting JavaScript into React Native Webview

Answer from Idan on Stack Overflow
Top answer
1 of 2
1

Try to inject js like this way:

   const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`;
    return (
      <View style={styles.container}>
        <WebView
          ref={ref => {
            this.webview = ref;
          }}
          source={{ uri: this.state.webViewUrl }}
          originWhitelist={['*']}
          injectedJavaScript={jsCode}
        />
      </View>
    );
  }

for more options take a look: Medium: Injecting JavaScript into React Native Webview

2 of 2
0

A few things off the top of my head:

  1. In your package.json, react-native version should be "react-native": "https://github.com/expo/react-native/archive/sdk-37.0.1.tar.gz", (Expo SDK 37 is already based on 0.61.4, but with Expo-specific mods). Getting expo-stripe-checkout working as before in previous versions may be as simple as this. The SDK 37 announcement blog post gives more info on the SDK upgrade process, namely:
    • Run expo upgrade in your project directory (requires the latest version of expo-cli, you can update with npm i -g expo-cli).
    • Make sure to check the changelog for other breaking changes!
    • ...
  2. If that doesn't help to get expo-checkout-stripe working again (fix your React Native version anyway, you're bound to have more issues with Expo if you don't), try one or both of the following with your webview:
    • Use injectJavaScript as per (Guide > Communicating between JS and Native > The injectJavaScript method)[https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#the-injectjavascript-method"]. In your case, that would be something like this.webview.injectJavaScript(jsCode)
    • Spitballing even more than the previous suggestions, but possibly try wrapping your webview's script tags in html/head/body tags. More due diligence/eliminating variables than anything else.

I hope one of these suggestions at least gets you on the right path.

🌐
GitHub
github.com › react-native-webview › react-native-webview › blob › master › docs › Guide.md
react-native-webview/docs/Guide.md at master · react-native-webview/react-native-webview
While you cannot execute arbitrary JavaScript, you can make an arbitrary JS object available to the JS run in the webview prior to the page load completing. <html> <head> <script> window.onload = (event) => { if (window.ReactNativeWebView.i...
Author   react-native-webview
Discussions

Injecting javascript prior to document load
Is there any way to inject javascript prior to the document loading? I think this would be related to #227 Thanks! More on github.com
🌐 github.com
69
January 2, 2019
React Native Webview how to use injectJavascript - Stack Overflow
I'm trying to set a global variable within a webpage loaded by a react-native WebView. I'm trying to set the global variable using the injectJavascript prop, but I'm getting an error telling me that injectJavascript is expected to be a function. More on stackoverflow.com
🌐 stackoverflow.com
javascript - injectedJavaScript is not working in Webview of react native - Stack Overflow
I am not able to inject this simple js code into react-native webview. I referred this link also but no solution provided here. Then I found this one which works for html props but not uri. import More on stackoverflow.com
🌐 stackoverflow.com
javascript - React Native Webview - injectJavascript not working - Stack Overflow
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? More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/reactnative › need help with react-native webview, injecting react native, into the javascript injection.
r/reactnative on Reddit: Need help with react-native Webview, injecting react native, into the javascript injection.
November 2, 2021 -

Confused, how do I get a string/state from my react native state, and make sure it's inside the javascript injection:

const [token, setToken] = useState("My RN token");

And the execution of the webview:

<WebView
        source={{html:home}}  
        javaScriptEnabled={true}
        injectedJavaScript={`alert(${token})`}
      />

The string interpolation doesn't work. What should I do if I'm trying to pass data from react native into the javascript string that's executed by the webview?

webviewRef.current.injectJavaScript("alert('myToken From React Native')");

Just for some more clarification the alerts were just testing to see if I can interpolate my RN states and their values into the webview code, what I would like to know is, how do I get my client token that I generated from my server, into the injectedJavascript code, for executing a braintree drop in ui:

<WebView
        source={{html:home}}  
        javaScriptEnabled={true}


        injectedJavaScript={`
                    
                      //code executed inside injected Javascript
                      //my token is inside my RN state, how do you use it here?
                     braintree.dropin.create({
                          authorization: 'MY_TOKEN_FROM SERVER',
                          container: '#dropin-container'
                        }, function (createErr, instance) {
                           
                            })
                           `
          }
      />

🌐
Medium
idanlevi2.medium.com › injecting-javascript-into-react-native-webview-521e4e55964b
Injecting JavaScript into React Native Webview | by Idan Levi | Medium
April 3, 2020 - import React, { Component } from 'react'; import { Text, View, StyleSheet } from 'react-native'; import { WebView } from 'react-native-webview';export default class app extends Component { constructor(props) { super(props); this.state = { webViewUrl: 'https://reactnative.dev' }; }render() { const jsCode = `document.querySelector('.HeaderHero').style.backgroundColor = 'purple';`; return ( <View style={styles.container}> <WebView ref={ref => { this.webview = ref; }} source={{ uri: this.state.webViewUrl }} originWhitelist={['*']} javaScriptEnabledAndroid={true} injectedJavaScript={jsCode} /> </View> ); } }const styles = StyleSheet.create({ container: { flex: 1, } });
🌐
Close
making.close.com › posts › react-native-webviews
Communicating with React Native Web Views | The Making of Close
January 15, 2024 - Things are not as straightforward when communicating to the web app from the native app. Rather than exposing an event-based system, React Native WebView allows you to inject arbitrary JavaScript code into the WebView at any time.
🌐
GitHub
github.com › react-native-webview › react-native-webview › issues › 229
Injecting javascript prior to document load · Issue #229 · react-native-webview/react-native-webview
January 2, 2019 - react-native-webview / react-native-webview Public · Notifications · You must be signed in to change notification settings · Fork 3.2k · Star 7.2k · New issueCopy link · New issueCopy link · Closed · Closed · Injecting javascript prior to document load#229 ·
Author   react-native-webview
🌐
Undefinednull
undefinednull.com › 2015 › 12 › 27 › injecting-custom-javascript-into-react-natives-webview
Injecting Custom JavaScript into React Native's Webview
December 27, 2015 - The injectedJavaScript is a custom prop of the React native Webview component. You can pass any JavaScript code ( as string ) to this prop, and React native will inject this JavaScript code into the Webview.
🌐
React Native Archive
archive.reactnative.dev › docs › 0.52 › webview
WebView · React Native Archive
Function that accepts a string that will be passed to the WebView and executed immediately as JavaScript. Set this to provide JavaScript that will be injected into the web page when the view loads.
Find elsewhere
🌐
SKPTRICKS
skptricks.com › 2019 › 01 › injecting-custom-javascript-into-react-native-webview.html
Injecting Custom JavaScript Into React Native Webview | SKPTRICKS
January 20, 2019 - This tutorial explains how to inject ... native Webview component. You can pass any JavaScript code ( as string ) to this prop, and React native will inject this JavaScript code into the Webview....
🌐
LogRocket
blog.logrocket.com › home › react native webview: a complete guide
React Native WebView: A complete guide - LogRocket Blog
August 12, 2024 - The react-native-webview package has several built-in features, including those for injecting JavaScript code, managing navigation and URL changes within the WebView, and customizing the loaded web content.
Top answer
1 of 7
12

Add onMessage method does work.

import React, { Component } from 'react';
import { Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component<{}> {
  render() {
    return 
      <WebView 
        javaScriptEnabled={true}
        injectedJavaScript={'alert("hello")'} 
        source={{uri:"https://www.google.com"}} style={{ marginTop: 20 }}
        onMessage={(event) => {
          console.log('event: ', event)
        }}
      />;
  }
}
2 of 7
8

Well, you have more than one issue here. First one is your web view needs to be wrapped in a containing View component with flex: 1. Second, injectedJavascript only accepts a string - not a function. Third, it seems you are attempting to use hello as a variable without defining it, or if it is a string than your syntax needs to be something like this: injectedJavascript={'alert("hello")'}. Furthermore, injectedJavascript is already fired when the view loads so you are all good there if that's what you are intending to do. You can inject javascript when the web view starts loading though, using a combination of the props, onLoadStart and injectJavascript, but the implementation is quite different, so that's a different question. Try this code:

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View,
  WebView
} from 'react-native';

export default class App extends Component {

  render() {
    let yourAlert = 'alert("hello")'
    return (
     <View style={{flex: 1}}>
       <WebView
        javaScriptEnabled={true}
        domStorageEnabled={true}
        injectedJavaScript={yourAlert}
        source={{ uri: "https://www.google.com" }} style={{ marginTop: 20  }} />
    </View>
   )
  }
}
🌐
GitHub
github.com › react-native-webview › react-native-webview › blob › master › docs › Reference.md
react-native-webview/docs/Reference.md at master · react-native-webview/react-native-webview
Inject any JavaScript object into the webview so it is available to the JS running on the page. ... Set a value to be used in JavaScript. Note: Any value in the object will be accessible to all frames of the webpage.
Author   react-native-webview
🌐
GitHub
github.com › react-native-webview › react-native-webview › issues › 2587
Call of injected JS function doesn't work on android · Issue #2587 · react-native-webview/react-native-webview
July 5, 2022 - function getBounds(query) { mapkit.init({ language: "en", authorizationCallback: function(done) { log("Authentication succeeded"); done("${Config.APPLE_MAP_TOKEN}"); }, }); search = new mapkit.Search({ language: "en", includeQueries: false, includePointsOfInterest: false, getsUserLocation: true, }); search.search(query, function (error, data) { if(data){const boundingRegion = data.places.map((place) => ({region: place.region.toBoundingRegion()})); document.ReactNativeWebView.postMessage(JSON.stringify(boundingRegion[0]));} }); } And call it: webview.current?.injectJavaScript('getBounds("${boun
Author   react-native-webview
🌐
Curiosum
curiosum.com › home › blog › react native › react native webview guide - build mobile app from existing web app
React Native WebView: Mobile App from Existing Web App Guide | Curiosum
December 16, 2025 - To handle communication from the native environment to the web using the following props: injectedJavaScript - injects given javascript code into the page after the document finishes loading,
Top answer
1 of 2
3

Look at the official document of the webview and see how to use it. Always refer to official documents when writing modules.

You can use this

const WebAPICode = `alert('Hello')`;
...
      <WebView
          ref={webView=> this.webView = webView}
          originWhitelist={['*']}
          source={{ uri: "http://10.0.2.2:3000/" }}
          javaScriptEnabled={true}
          injectedJavaScript={WebAPICode}
        />

If you have this function on your web, you can call it.

<html>
<head>
    <script language="javascript">
    function test()
    {
         alert('Hello');
    }
   </script>
</head>
<body>
...
const WebAPICode = `test()`;
...
      <WebView
          ref={webView=> this.webView = webView}
          originWhitelist={['*']}
          source={{ uri: "http://10.0.2.2:3000/" }}
          javaScriptEnabled={true}
          injectedJavaScript={WebAPICode}
        />

To execute the data shown in the comments, you have to do this.

Your webview page do this

var data = {name: "getname"}
window.ReactNativeWebView.postMessage(data);
  handleMessage(e) {
    //여러 데이터가 리스트 형식으로 올때
    let parsedata = JSON.parse(e.nativeEvent.data);
    message = parsedata.name
    if(message == "get name") {
       const data = { name: "John"  }
    this.webview.postMessage(JSON.stringify(data));
    } 
  }
<WebView
 ref={webview => (this.webview = webview)}
 onMessage={mssage => this.handleMessage(mssage)}
}

Receive webview page

document.addEventListener("message", function(event) {
    console.log("Received post message", event);

    test(event.data);
}, false);
2 of 2
1

You can call postMessage from webview and set your webview onMessage props like this.

onMessage={event => { console.log(event) } }

In your webview html:

window.ReactNativeWebView.postMessage("Your Message");