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

How can we identify if a React component is stateless/functional?

Two types of components exist in my React project: functional/stateless and those inherited from React.Component: const Component1 = () => (<span>Hello</span>) class Component2 extends React.Component { render() { return (<span> ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

Uploading a screenshot to a server using Ionic 4

I have encountered an issue while trying to take a screenshot and upload it to a server using the spring-boot. I utilized a native library for taking the screenshot and an Angular service to obtain the image URI. I converted the image URI to a blob and sen ...

Executing multiple selections using the Selenium Webdriver

Is there a way to simulate a multiple selection scenario using Selenium webdriver where the user can select Item 1 and Item 5 specifically without selecting the items in between? URL JQuery Selectable I have attempted to achieve this by utilizing the cli ...

Viewer model aggregation - coordinating problem

In the Viewer, I am dynamically aggregating models from multiple BIM files. The process involves initializing the viewer and then using LoadDocument and LoadModel for each model chosen by the user. These models are primarily NVC files (the ones I used for ...

A guide to incorporating a textview into a React application using the Google Maps API

Wondering how to incorporate a textview within a react-google-maps component? Successfully setting up a Google map page in React using the react-google-maps API, I've managed to insert markers and link them with polylines. import React from "react"; ...

Difficulty comprehending the fallback for JSON.parse in jQuery.parseJSON

Check out the origin of $.parseJSON function (data) { if (typeof data !== "string" || !data) { return null; } // Remove leading/trailing whitespace for compatibility data = jQuery.trim(data); // Try native JSON parser first ...

The Jquery append() method seems to be having issues specifically in the Internet Explorer

I am a jQuery 1.10.2 version with the task of inserting an XML node at a specific location within an existing XML structure. To achieve this, I am utilizing the jQuery `append()` function successfully in Chrome, Firefox, and IE Edge; however, it is encount ...

Comparing the distinction between the unique constraint annotation in Hibernate and utilizing a PostgreSQL query

Currently, I am working with Hibernate and Postgresql in my project. I have some columns in my database that need to have a Unique constraint. After some research online, I found two methods to achieve this. First method using Postgresql query: ALTER TA ...

Retrieve the 'current' scope using a 'master' controller

I have a main controller that I refer to as my 'root' controller, which is declared using the ng-controller attribute. Additionally, I have a few other controllers that are created dynamically through a $routeProvider. I want to define a function ...

What is the most effective way to extract the value of a "$3" element using Selenium in Python?

I am facing a challenge in fetching an element from the netlify dashboard. The code I have currently grabs the base element that the web developers have set, indicating that it gets updated with javascript. However, I am having trouble accessing this updat ...

Using Javascript and JQuery to create an alert that pops up upon loading the page is not effective

I am having trouble making an alert show up when my website loads. The Javascript code is functional when directly included in the HTML, but once I move it to a separate file named script.js and link it, nothing happens. Can someone please help me identify ...

The absence of parentheses in the @query Java JPA statement was noticed

Currently, I am executing a query in a @repository class Here is the code snippet: @Query(value="(SELECT * FROM cor_documento WHERE ENVIADA_RECIBIDA = 'R' AND NVL(CANAL, ' ') != 'SDQS' AND fecha_Rad > :fechaRad order ...

Efficiently sending VueJS data to a separate script

I am in the process of transitioning an existing site to VueJS, but I have encountered a roadblock when it comes to finding the best method to accomplish this task. The site currently utilizes D3-Funnel (https://github.com/jakezatecky/d3-funnel) to genera ...

What is the reason for getting a null return when attempting to access a resource within a Jar file using a URL

I am facing an issue with a specific Jar file called core.jar: META-INF/... com/... config myLog4j.xml schema The problem arises when trying to read/load a class located in com/my/company/MyLogging.class. Within the MyLogging class, I have the followi ...

JavaScript Decoding JSON with varying identifiers

The JSON data provided contains information about different types of vehicles, such as cars, buses, and taxis. { _id:"7654567Bfyuhj678", result:{ CAR:[ [ "myCar1", 12233 ], [ ...

What is the best way to integrate JavaScript into an Express Handlebars template using partials?

In my current project, I have utilized the following handlebars template (located under views/layouts/main.handlebars): <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>{{title}}</title> ...

What is the correct method for adjusting the height properties of an element?

I'm trying to adjust the height of my div using the code below var heightMainDiv = window.innerHeight - 50; var myDiv = $("#main_content")[0]; myDiv.clientHeight = heightMainDiv; myDiv.scrollHeight = heightMainDiv; However, the values of clientHeigh ...

What is the best way to limit the number of items shown in a cart dropdown using JavaScript

I have a shopping cart feature added to my ecommerce web app. Within the header, there is an icon of a cart. When clicked, a dropdown appears showing the items added to the cart. However, if I have 10 items in the cart, the dropdown becomes too lengthy to ...