Issue with injecting Javascript function in Android React Native WebView, while it functions correctly on iOS React Native platforms

Encountering a challenge while implementing webview functionality. I am attempting to inject a JavaScript function into my webview, but it seems to only be functioning properly on iOS and not on Android.

Take a look at my code :

Webview :

<WebView
                            source={{uri:"http://mywebview.com/webview.php"}}
                            injectedJavaScript={jsCode}
                            mixedContentMode={'compatibility'}
                            javaScriptEnabledAndroid={true}
                            style={{height: 300}} />

Javascript Code to Inject :

let jsCode = `function doPopUp() {
                        document.querySelector('#myBody').style.backgroundColor = 'red';
                        alert('hello world from webview');
                        }`;

The JS injection works fine on iOS, but encounters issues on Android. However, when I directly include the JS code in the php file and open it in an Android browser, it works perfectly. Interestingly, if I remove the syntax inside the JS function, it also works fine. What could be causing this discrepancy and how can I resolve it?

Answer №1

After several hours of troubleshooting, I finally found a solution to the issue at hand. This particular method seems to do the trick.

Interestingly, without utilizing the ref attribute, the injectedJavaScript won't execute as expected. However, once the ref is set and

webViewRef.current.injectJavaScript(runFirstScript);
is implemented, the injectedJavaScript works seamlessly.

This problem was isolated to IOS and did not affect android devices.

I also shared this fix on the github issues page for react-native-webview: https://github.com/react-native-webview/react-native-webview/issues/2259

 ...
 
  const webViewRef = useRef();

 const runFirstScript = `
      document.body.style.backgroundColor = 'red';
      setTimeout(function() { window.alert('hi') }, 2000);
      true; // note: this is required, or you'll sometimes get silent failures
    `;
    
    const runSecondScript = `
      setTimeout(function() { window.alert('hello') }, 2000);
      true; 
    `;

  if (webViewRef.current != null) {
    webViewRef.current.injectJavaScript(runSecondScript);
  }
  return (
    <>
      <WebView
        ref={ref => (webViewRef.current = ref)}
        cacheEnabled={true}
        injectedJavaScript={runFirstScript} // now injectedJavaScript will trigger along with the ref.
        javaScriptEnabled
        mixedContentMode={'compatibility'}
        onMessage={event => {
          //    alert(event.nativeEvent.data);
        }}
        originWhitelist={['*']}
        scalesPageToFit
        source={{uri: 'https://example.com'}}
        startInLoadingState={true}
        userAgent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"
      />
    </>
  );

Answer №2

When integrating a javascript function for android, it is crucial to incorporate it into the DOM structure. To achieve this, replace function with document within jsCode.

let jsCode = `document.doPopUp() {
                        document.querySelector('#myBody').style.backgroundColor = 'red';
                        alert('hello world from webview');
                        }`;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unresolved promise rejection in a React application

I attempted to run npm start and encountered the following error message: “(node:4786) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error occurred due to either throwing an error inside an async function without a catch block, or r ...

The page fails to redirect to the intended page when provided with an incorrect URL

I am currently working with an Angular function that I have provided below. Function : 404.html file located in the root folder.</p> The issue I am encountering is that despite no errors appearing in the console, the URL in the address bar always ...

Angular JS - Implementing a flexible URL structure for fetching data using $http GET

I have been working on implementing a login feature for my app by using a custom REST API. Initially, I was able to successfully authenticate by manually entering the complete URL with the username and password: http://www.myexample.com/ACTION/USER/PASSWO ...

How can I incorporate multiple graphs into my AmCharts display?

I am new to using amcharts and have successfully implemented a code snippet to generate two graphs in a chart. The charts are loaded from an external data source specified in the code. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "d ...

Iterate through elements within an HTML table by utilizing jQuery

I have a table. My goal is to loop through all the items in the table and extract their quality and price data. However, I'm struggling to access these values efficiently. Here is the structure of the table: <div class="table-items__container"&g ...

"Which is the better choice for a Django application's for loop: views.py or

I'm in the process of creating a Django app that features a word list. The app currently utilizes a speech function to inform the user of the first word on the list. The user is then able to record an audio clip of a word they say, which is converted ...

Verify the accurate sequence for arranging the items in the drag and drop list

I am currently developing a Language learning platform that includes several web applications. I am still new to javascript and struggling to find a solution for one of my apps. This specific app involves draggable list items that need to be arranged in t ...

"Populate the input fields in a table with the data retrieved from the AJAX request's

For my current project, I am utilizing an ajax request to select data from a database. The selected data includes the area and floor number of a building, formatted as follows: "storey": [{ "storeyno": "1st Floor", &qu ...

Unable to halt the multiplexer

I am encountering an issue with the media muxer in my app. What could be causing it to crash, and how can I resolve this problem? java.lang.IllegalStateException: Failed to stop the muxer at android.media.MediaMuxer.nativeStop(Native Method) at an ...

The ASP input class fails to trigger the JavaScript function

Within my ASP page, I am working with two input elements: <input type="text" class="arrivalDate form inp compare_prices_fields datepicker total_price_fields price_list_fields allRows" id="calc_arrdate_group_0" value="" style="width: 95px" rbo_id="Arriv ...

The localstorage in Ionic 3 with Angular 5 consistently returns a null value when attempting to retrieve the stored value

I recently incorporated the storage plugin into my ionic 3 app (with angular 5). The documentation seemed pretty clear... or so I thought. Oddly enough, I am able to successfully store values (which are visible in debug tools), but I am unable to retrieve ...

Utilizing Mongoose Schema for CSV Import

My current task involves importing a large CSV file into a mongo DB, where the order of the values will determine the key for each entry in the database: Here is an example of the CSV file structure: 9,1557,358,286,Mutantville,4368,2358026,,M,0,0,0,1,0 9 ...

There seems to be a partial malfunction of the mailto function in AS3 when used on

After creating a small SWF game using AS3, I added a form at the end to capture users' details and send them via a mailto function. Everything was working perfectly on the desktop, but when I tested it on a tablet, the mailto function worked fine exce ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Can Node.js handle parsing this as JSON?

Attempting to parse a small API that returns somewhat invalid JSON. Trying the following approach: var request = require('request'), url = 'urlhere'; request({ url: url }, function(error, response, body) { ...

What could be the reason for Jest throwing an error during the testing of the `Colyseus` game?

Currently, I am evaluating the functionality of a game using Jest as both a testing framework and assertion library. Below is my test configuration: const { Server } = require("colyseus") const { ColyseusTestServer, boot } = require("@colyse ...

The presence of the If-Modified-Since header causes the CORS OPTIONS request to experience failure

When using a custom header (If-Modified-Since) in the code below, it causes ajax to fail with a status of HTTP/1.1 405 Not Allowed for the OPTIONS preflight request. However, if the header is removed, the request works as expected (I am unsure if OPTIONS i ...

Is the Bootstrap success icon displaying in white on white instead of the traditional green color?

I recently sourced code directly from the Bootstrap documentation (see below), but I'm encountering an issue where my "success" badge appears as white text on a white background. The text is there, as I can highlight it, but it's not displaying c ...

I'm looking for the best way to send POST data to an API with Meteor's HTTP package

Here's my current code snippet: HTTP.post("http://httpbin.org/post", {}, function(error, results) { if (results) { console.log(results); } else { console.log(error) } ...

The function correctly identifies the image source without error

I possess a pair of images: <img id="img1" src="l1.jpg" usemap="#lb" height="400" border="0" width="300"> <img src="images.jpg" id="img2"> Next up is some JavaScript: function validateImages () { if (document.getElementById('img2&ap ...