Transferring String data between Java and JavaScript using Webview in both directions

I'm currently developing an application that allows two users to communicate via a webview. My goal is to transfer a String variable from JavaScript to Java in order to store it in my SQLite database, and also be able to do the reverse operation as well.

Answer №1

Invoking Java/Kotlin code from JavaScript

If you need to trigger Java or Kotlin code from your JavaScript, Android WebView offers a solution known as Javascript Interface.

This feature enables the execution of java/kotlin functions from within your javascript code.

To accomplish this, you can create an interface like so:

val webView: WebView = findViewById(R.id.webview)
webView.addJavascriptInterface(WebAppInterface(this), "Android")

In this snippet, WebAppInterface defines the methods that can be invoked from javascript.

/** Create an instance of the interface and provide the context  */
class WebAppInterface(private val mContext: Context) {
     /** Display a toast on the web page  */
     @JavascriptInterface
     fun showToast(toast: String) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show()
     }
}

The name "Android" serves as the bridge between your webview and javascript, allowing for method calls in the latter.

With this setup, calling these methods from your javascript becomes possible:

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
    Android.showToast(toast);
}
</script>

Note that callbacks from the interface do not always occur in the main thread. To execute UI-related tasks, remember to utilize runOnUiThread.

Triggering JavaScript function from Java/Kotlin code

For scenarios where you need to call javascript functions from your Java or Kotlin code in Android WebView, you can leverage the Evaluate Javascript feature introduced in API level 19.

Here's an example with the following javascript method:

<script type="text/javascript">
function printName(name) {
    console.log(name); 
}
</script>

You can invoke this JavaScript function using the following code:

yourWebview.evaluateJavascript("printName(\'TEST\')")

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

Learn how to utilize ng2-file-upload in Angular for uploading .ply files effortlessly!

I'm currently working on uploading various files using ng2-file-upload. I've been successful in uploading different file types like png and jpg, but I'm facing an issue with the .ply file extension. Can someone guide me on how to upload a fi ...

Incorporating various language URLs in Next.js using next-i18n-next functionality

Thinking about using the next-i18next internationalization library. Check out next-i18next on GitHub Curious about how to change the language in the path of my URL. For example: /about-us /over-ons -> takes you to the Dutch version of the about us p ...

Automatic button rotation

I managed to set up a button that works on click with a delay, making it semi-automatic. However, I'm struggling with getting it to not pause after just one click. Here's what I have so far: <!DOCTYPE html> <html> <body> &l ...

Can you explain the concept of a framework operating "on top of" node.js in a way that would be easy for a beginner to understand?

If someone is new to JavaScript, how would you explain the concept of "on top of node.js" in simple programming language? I am looking for a general explanation as well as specific reference to Express on top of node.js in the MEAN stack. Appreciate your ...

Express npm dependency fails to start globally

I have recently reinstalled my operating system from Windows 8.1 to Windows 8.1, and I have been using npm for quite some time. Previously, it was working fine as mentioned here. After the reinstallation, I tried installing npm i -g express, but it does n ...

Combine multiple arrays in JavaScript into a single array

Here is the array I am working with: array = ['bla', ['ble', 'bli'], 'blo', ['blu']] I need to transform it into this format: array = ['bla', 'ble', 'bli', 'blo', &a ...

Ways to detect scrolling activity on the v-data-table module?

Are you looking for a way to detect scrolling events on the v-data-table component in Vuetify framework? I am referring to the scenario where the table has a fixed height, causing the table body to scroll. <v-data-table fixed-header :height=400 : ...

Using an object does not result in updated data, while data changes are typically observed when using a variable

In the process of developing a function to update a custom checkbox upon clicking (without resorting to using the native checkbox for specific reasons). Here's the code snippet for the checkbox: <div class="tick-box" :class="{ tick: isTicked }" @ ...

Tips for transferring the button ID value to a GET request?

I recently developed a Node.js application that interacts with a database containing student information and their current marks. Utilizing MongoDB, I retrieve the data and present it in a table within an .ejs file. index.js router.get("/dashboard", funct ...

Utilizing ion-slide-box within an ion-content container that allows for scrolling

I've created an Ionic view with the following structure: <ion-content scroll="true"> <ion-list> ... some ion items... <ion-item> <ion-slide-box> <ion-slide ng-repeat="image i ...

Unable to retrieve the status for the specified ID through the use of AJAX

When I click the button in my app, I want to see the order status. However, currently all statuses are being displayed in the first order row. PHP: <?php $query = mysqli_query($conn, "SELECT o.orderid,o.product,o.ddate,o.pdate,k.kalibariname,o.sta ...

An issue has occurred in AngularJS where the error message "ng areq not

I'm facing an issue with my meta controller, as I am trying to alter the meta tags dynamically. When checking the console, I encounter the error message error ng areq not a function. I have looked on StackOverflow for similar issues but couldn't ...

ng-init assign value to a new object

<!DOCTYPE html> <html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script> <body> <div ng-app="myApp" ng-controller="myCtrl2" ng-init="person = new Person('Al ...

Problem encountered when attempting to add elements to an array within a nested

When running this code, everything works correctly except for the array pushing. After checking the console.log(notificationdata), I noticed that notification data gets its values updated correctly. However, when I check console.log(notifications), I see ...

Creating a React functional component that updates state when a specific window breakpoint is reached

Having an issue with my code when it hits the 960px breakpoint. Instead of triggering once, it's firing multiple times causing unexpected behavior. Can someone help me troubleshoot this problem? const mediaQuery = '(max-width: 960px)'; con ...

Performing an ASync call to the GetData routine in MongoClient using NodeJS

Combining code snippets from https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%20the%20async%20keyword%20before,a%20promise%20to%20be%20resolved. Upon ob ...

Having trouble running Javascript with jQuery's ajax load()?

I have encountered this problem and despite reading multiple posts, I am unable to find a solution. My challenge lies in loading an HTML file into a div that contains an unordered list. The list is supposed to function as an expanded menu with sub-items, ...

Menu changes when hovering

I want to create an effect where hovering over the .hoverarea class will toggle the visibility of .sociallink1, .sociallink2, and so on, with a drover effect. However, my code isn't working as expected. Additionally, an extra margin is automatically ...

Replacing jQuery.ajax from a different directory/domain - problem with using relative URLs

We are incorporating scripts from various sources and domains, including one that contains the definition for jQuery.ajax function. Calls to jQuery.ajax are being made from different places and domains using relative URLs, such as jQuery.ajax("my/relativ ...

What could be causing my Angular code to submit back unexpectedly?

My goal is to make an initial call to the database to populate some dropdowns, after which all actions are done through AJAX. However, whenever I click a button on the page, it seems to be posting back and calling the function that fetches dropdown values ...