Using Android WebView to run JavaScript code

My HTML file has the following structure:

<html>
<head>
     This is a test
    <script>
    function testingConsole() {
    console.log("Reached end of Body");
    }
    </script>


</head>

<body>
    <script type="text/javascript">testingConsole();</script>
</body>
</html>

Here's how my code looks like:

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.chart);

    webView = (WebView) findViewById(R.id.wvChart);
    webView.loadUrl("file:///android_asset/Chart/chart.html");
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient());

    webView.loadUrl("javascript:testingConsole();");
}

While the HTML file loads correctly and displays "This is a test" in the WebView, the script `testingConsole();` executes on its own when called from the HTML file. However, when I try to call it from my code, I encounter an error stating "Uncaught ReferenceError: testingConsole is not defined at null:1"

Answer №1

The loadUrl(String) method in the WebView is not executed synchronously; it operates on separate threads to handle page loading and JavaScript execution.

To ensure proper execution, you should develop a custom implementation or subclass of WebViewClient that specifically overrides the onPageFinished(WebView, String) method. This will allow for monitoring when the webview finishes loading "chart.html." Once this occurs, you can proceed to call the second loadUrl containing your JavaScript code. Although untested, I believe this approach will yield successful results. Please provide feedback if implemented.

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

It is not possible to redirect to a Facebook profile page with the Facebook app installed

Having trouble with linking to a Facebook profile page when the Facebook app is installed. It shows that the page is not available. However, when the Facebook app is not installed and the page is opened in a browser, everything works perfectly. Any sugge ...

Update only one field at a time using the REST API

Currently, I am developing an inline grid editor that triggers a call to an express rest api whenever a user updates a single value in the grid. The issue I am facing is that when a field is changed, my PATCH request attempts to update all fields instead o ...

An error occurred during conversion: trying to convert an object to an array

After reading numerous articles about this issue and trying multiple solutions, I am still unable to resolve it! I have been stuck with this error for the past 3 days and I'm hoping someone can assist me. Thank you in advance for any help! My situati ...

What should the website do if none of the paths are found - direct to a 404 error page?

<Routes> {!userlog ? ( <Route path="/" element={<AuthLayout />}> <Route index element={<Login />} /> <Route path="/login" element={<Login />} /> <Route path="/sig ...

Steps for extracting a URL from a PHP hyperlink containing post data

In the process of developing a downloads page that generates custom file download URLs using DLGuard after a purchase, I encountered an interesting challenge. For instance: <a href="downloadfile.php?r=11034705&p=42">Download</a> This hyp ...

Connect two selection boxes' values with a single knockout date attribute

I am currently working with a knockout object that consists of a single property named created. The created property contains a Date object which represents the date of an event. In my HTML form, I have two select box inputs: one for selecting hours and th ...

Generate a dynamic HTML table using an array of objects

I have a dataset that I need to transform into an HTML table like the one shown in this image: https://i.sstatic.net/gRxJz.png Despite my attempts to write the code below, it seems that the rows are being appended in different positions. Is there another ...

Why is my React Native TouchableOpacity onPress function not functioning properly?

Embarking on my journey with React Native (or any JS framework for that matter), I decided to delve into creating a simple tap game. The concept is straightforward: tap on the blue square, watch it randomly relocate, and repeat the process. Here is a snipp ...

Remove HTML tags from user-editable content

I need to save contenteditable data into a JavaScript array, with each new line being a separate array item. Initially, I cleared out Chrome's HTML like this: html = html //empty line looks like this: .replace(/<div><br\s*[\/]?> ...

What is the best way to bring an image into your nextjs project?

I have a question about importing images into my Next.js project. I created an array of objects and want to import an image stored in a folder on my laptop, specifically in the src folder rather than the public folder. How can I properly achieve this in ...

Reorganizing JSON Information

Currently, I am dealing with a JSON file that contains multiple sets of data structured like this: {"name": ["Adelphi University"], "supp": ["Yes: E, WS"], "ed": ["\u00a0"], "online": ["$40"], "ea": ["12/1"], "mid": ["No"], "rd": ["Rolling"], "recs": ...

Having trouble with transmitting a JSON array to a Node.js server using AJAX

When sending data via AJAX to my nodejs server, I use the following JavaScript on the client side: function login(){ var array=[]; var jsonData={}; jsonData.user=$('#user').val(); jsonData.pass=$('#pass').val(); arr ...

Should we consider the implementation of private methods in Javascript to be beneficial?

During a conversation with another developer, the topic of hacking into JavaScript private functions arose and whether it is a viable option. Two alternatives were discussed: Using a constructor and prototype containing all functions, where non-API meth ...

Task ':game_services:compileDebugKotlin' encountered an unsuccessful execution

I have integrated the games_services package into my Flutter app, but I am encountering an issue when trying to run the app on an Android emulator. The error message I am receiving is as follows: FAILURE: Build failed with an exception. * What went wrong: ...

Tips for incorporating Emoji into a messaging platform similar to SendBird (non-native, web-based application)

Hey everyone! I'm currently working on a project that involves integrating the "SendBird" messaging service. I've successfully implemented all the basic functions, but now I want to incorporate Emoji for better user experience. I'm feeling a ...

"Error: The chai testing method appears to be improperly defined and is not

I am trying to set up a Mocha and Chai test. Here is my class, myClass.js: export default class Myclass { constructor() {} sayhello() { return 'hello'; }; } Along with a test file, test.myclass.js: I am attempting to a ...

Ways to clear the cache on a webpage after updating scripts

After scouring the internet for a way to update user cache when a website is modified, I came up empty-handed. The only suggestion I found was setting version control on the URL of the script files... Below, I'm sharing my own solution and I'm w ...

Issue encountered when assigning a new value to a private class property at a global scope in JavaScript

I am encountering an issue in my code where I define a private class member using "#", initialize it in the constructor, and then receive an error when attempting to set/access the value. Uncaught TypeError: Cannot read private member #mouse from an object ...

What are some ways to slow down the speed of a canvas animation?

I am currently working on an animation project using JavaScript and canvas. I have a reference fiddle where objects are generated randomly and fall from the top right corner to the bottom left corner, which is fine. However, the issue is that the objects a ...

Guide on retrieving a value from a function that invokes $.getJSON

function searchAndRetrieve(searchTerm) { var defaultResult = 1010; var resultValue = defaultResult; $.getJSON(remote, function(data) { if (data != null) { $.each(data.items, function(i, item) { ...