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)
        }}
      />;
  }
}
Answer from AmazingBeerBelly on Stack Overflow
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>
   )
  }
}
🌐
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, } });
Discussions

Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.
Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.#341 ... We're trying to migrate from react-native WebView. More on github.com
🌐 github.com
33
February 13, 2019
React Native Webview how to use injectJavascript - Stack Overflow
injectedJavaScript is the prop that injects JS into the web view, once, when it loads. This is what you seem to want. How injectJavascript is used on the other hand? it's by calling it on the ref of the webview to inject more JS programmatically on the fly. More on stackoverflow.com
🌐 stackoverflow.com
injectedJavaScript is not working in IOS
Bug description: I am using "react-native-webview": "^10.10.2". I am using "injectedJavaScript" in webview, this property is working fine in android but not working in... More on github.com
🌐 github.com
8
December 9, 2020
injectedJavaScript executed multiple times
The injectedJavaScript prop -This is a script that runs immediately after the web page loads for the first time. It only runs once, even if the page is reloaded or navigated away. When script inside a page loaded in webview creates react-router createHashRouter() webview reloads and ... More on github.com
🌐 github.com
8
December 26, 2024
🌐
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) {
                           
                            })
                           `
          }
      />

🌐
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
If false, (only supported on iOS and macOS), loads it into all frames (e.g. iframes). ... Inject any JavaScript object into the webview so it is available to the JS running on the page.
Author   react-native-webview
🌐
GitHub
github.com › react-native-webview › react-native-webview › issues › 341
Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. · Issue #341 · react-native-webview/react-native-webview
February 13, 2019 - Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.#341 ... We're trying to migrate from react-native WebView.
Author   react-native-webview
🌐
React Native Archive
archive.reactnative.dev › docs › 0.52 › webview
WebView · React Native Archive
import React, { Component } from ... 20}} /> ); } } You can use this component to navigate back and forth in the web view's history and configure various properties for the web content....
🌐
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.
🌐
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
injectedJavaScript runs a method on WebView called evaluateJavaScript:completionHandler: – this is no longer true as of version 8.2.0. Instead, we use a WKUserScript with injection time WKUserScriptInjectionTimeAtDocumentEnd. As a consequence, injectedJavaScript no longer returns an evaluation value nor logs a warning to the console.
Author   react-native-webview
Find elsewhere
🌐
GitHub
github.com › react-native-webview › react-native-webview › issues › 1779
injectedJavaScript is not working in IOS · Issue #1779 · react-native-webview/react-native-webview
December 9, 2020 - render() { return ( <WebView source={{ uri: "https://www.helpmefund.org/campaigns" }} injectedJavaScript={this.myScript()} /> ); } }
Author   react-native-webview
🌐
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 custom javascript in webview component in react native application.The injectedJavaScript is a custom prop of the React native Webview component.
🌐
LogRocket
blog.logrocket.com › home › react native webview: a complete guide
React Native WebView: A complete guide - LogRocket Blog
August 12, 2024 - If you look at the WebView component, you will notice that we have introduced three new props: onMessage, injectedJavaScript, and injectedJavaScriptBeforeContentLoaded.
🌐
GitHub
github.com › react-native-webview › react-native-webview › issues › 3656
injectedJavaScript executed multiple times · Issue #3656 · react-native-webview/react-native-webview
December 26, 2024 - The injectedJavaScript prop -This is a script that runs immediately after the web page loads for the first time. It only runs once, even if the page is reloaded or navigated away.
Author   react-native-webview
🌐
GitHub
github.com › henrychuangtw › WebView-Javascript-Inject
GitHub - henrychuangtw/WebView-Javascript-Inject: Android webview inject javascript with addjavascriptinterface, intercept and get post data · GitHub
Android webview inject javascript with addjavascriptinterface, intercept and get post data - henrychuangtw/WebView-Javascript-Inject
Starred by 68 users
Forked by 24 users
Languages   Java
🌐
Inappwebview
inappwebview.dev › docs › webview › javascript › injection
Injection - Javascript - InAppWebView
To evaluate JavaScript code, you can use the InAppWebViewController.evaluateJavascript method. It accepts a String as source code to be evaluated by the WebView and an optional Content World and returns the result of the evaluation as a dynamictype.
🌐
42Gears
techblogs.42gears.com › home › inject javascript to android webview
Inject JavaScript to Android WebView - Tech Blogs -
September 21, 2022 - The problem statement is when we want to load specific JavaScript on the loaded webpage within WebView in any Android Application. There are two ways to achieve the results : 1. By using loadUrl() -> API level 18 and below With loadUrl(), the UI will be refreshed when the script is applied and it doesn’t […]
🌐
javaspring
javaspring.net › blog › injectedjavascript-is-not-working-in-webview-of-react-native
React Native WebView: Why is injectedJavaScript Not Working with URI? [Troubleshooting & Fix]
React Native’s `WebView` component is a powerful tool for embedding web content (local or remote) into mobile apps. A key feature is `injectedJavaScript`, which lets you run custom JavaScript code directly in the context of the loaded web page. ...
🌐
GitHub
github.com › facebook › react-native › issues › 11581
WebView not updated with injected javascript SOLVED · Issue #11581 · facebook/react-native
December 21, 2016 - // @flow 'use strict'; import React, { Component } from 'react'; import { StyleSheet, View, Image, Text, TouchableHighlight, WebView } from 'react-native'; export default class WebViewTest extends Component { constructor(props) { super(props); this.state = { timesClicked : 0 }; this._onPressButton = this._onPressButton.bind(this); } _onPressButton() { let timesClicked = this.state.timesClicked; timesClicked++; console.log(timesClicked + " Clicked "); this.setState({ timesClicked: timesClicked }); this.refs.myWebView.postMessage("This is my land times " + timesClicked); } render() { let html =
Author   facebook
🌐
Vercel
wirescript.vercel.app › blog › how-to-use-webview-in-react-native
How to use Webview in React Native? | The Wirescript
import React from "react"; import { View } from "react-native"; import { WebView } from "react-native-webview"; const App = () => { const scripts = ` document.body.style.backgroundColor = 'hotpink'; document.querySelector("h1").style.color = 'skyblue'; document.querySelector("p").style.padding = '20px'; true; `; return ( <View style={{ flex: 1 }}> <WebView source={{ uri: "https://www.example.com/" }} injectedJavaScript={scripts} /> </View> ); }; export default App;