Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog in JS with the mentioned annotation and have implemented a switch statement to decide which function to call in JS. Despite using a flag, the synchronization problem is causing the method showDialog() to execute before the Dialog appears. Is there a solution for seamlessly managing bidirectional communication between Android and JavaScript?

@JavascriptInterface
public int showDialog(){
    new AlertDialog.Builder(this.activity)
            .setTitle("Share image as...")
            .setItems(new CharSequence[]{"Image", "PDF document", "Print"}, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which){ // This switch statement determines the JS function to call
                        case 0: chosenMethod = 0; // Here is where the JS function should be invoked (e.g., exportImage())
                            Log.v("Dialog onClick()", "Method chosen" + chosenMethod);
                            break;
                        case 1: chosenMethod = 1;
                            Log.v("Dialog onClick()", "Method chosen" + chosenMethod);
                            break;
                        case 2: chosenMethod = 2;
                            Log.v("Dialog onClick()", "Method chosen" + chosenMethod);
                            break;
                    }
                }
            })
            .create().show();
    Log.v("Dialog out of onClick", "Method chosen" + chosenMethod);
    return chosenMethod;
}

Answer №1

If you want to execute a JavaScript function after loading a webpage in your webview, you can use the following code snippet:

webView.loadUrl("javascript:doSomething()");

Remember to ensure that your webview settings allow for JavaScript execution and have proper security configurations in place.

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

Receive a notification when the div element stops scrolling

I am attempting to replicate Android's expandable toolbar within an Angular component. My HTML code appears as follows: <div (scroll)="someScroll($event)"> <div class="toolbar"></div> <div class="body"></div> </d ...

What is the best way to add a single space between numbers in a JSON string using Java?

Within the code snippet below, I am constructing a JSON string using gson: private String generateData(Map<String, Map<Integer, Set<Integer>>> nodeTable, int i) { JsonObject jsonObject = new JsonObject(); Set<Inte ...

Issue with implementing bootbox and jQuery.validator for AJAX login form collaboration

Here's a fiddle link that showcases the issue I'm facing. The problem arises when I try to Sign In on an empty modal form. The validator should highlight any fields in error and proceed to submit the form once the validation is successful. I&ap ...

Tips for resolving the Error: Hydration issue in my code due to the initial UI not matching what was rendered on the server

export default function Page({ data1 }) { const [bookmark, setBookmark] = useState( typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('bookmark')) : [] ); const addToBookmark = (ayatLs) => { s ...

What is the best way to search for a specific value within a nested JSON object and determine if it meets certain criteria?

In my table on a parse server platform called back4app, I have the following data: [{ "companyName":"Abc Ltd", "branchAddress":"1-1,Xyz Street", "empInfo": {"name":"Naveen", ...

Module-alias cannot be resolved by esm

Currently, I am utilizing the combination of esm package and module-alias. However, it appears that esm is not recognizing module-alias's paths. This is how I am loading my server file: nodemon -r esm ./src/index.js 8081 At the beginning of my inde ...

Exploring a JSON Object with Nested Data

I am trying to recursively parse a JSON object in JavaScript. Below is an example of the JSON structure: const obj = { tag: 'AA', type: 'constructed', value: 'ABCD1', child: [ { tag: 'BB', ty ...

Converting php array submitted from a form using ajax

I have a form on my website that collects user input and sends it to an email address using php. The form includes a checkbox input where users can select multiple options, which are then stored in an array. However, when the form is submitted, the email r ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

What is the process of sending a file from a remote URL as a GET response in a Node.js Express application?

Situation: I am working on a Multi-tier Node.js application with Express. The front end is hosted on an Azure website, and the back end data is retrieved from Parse. I have created a GET endpoint and I want the user to be able to download a file. If the f ...

Having trouble with window.setInterval in AngularJS?

My coding snippet involves the use of the setInterval method: function MyController($scope) { $scope.clock = new Date(); var updateClock = function() { $scope.clock = new Date(); }; setInterval(updateClock, 1000); }; The HTML asso ...

Discover the security vulnerabilities in Node.js when using VS Code with FREECODECAMP's React app

As a beginner in using VS code, I attempted to work on a project for FREECODECAMP. This project involved creating a random quote machine, marking my first time coding a react project. While following a YouTube tutorial and making progress towards functiona ...

Tips for verifying an alphanumeric email address

I need to create an email validation script that allows only alphanumeric characters. <script type = "text/javascript"> function checkField(email) { if (/[^0-9a-bA-B\s]/gi.test(email.value)) { alert ("Only alphanumeric characters and spaces are ...

Adjust the Placement of Images in Relation to Mouse Movements

Is there a way to creatively animate the positions of images or background images based on mouse movement? Let's take Github, for instance: https://github.com/thispagedoesntexist The 404 page on Github is truly impressive. I aim to captivate my use ...

Should we retain the express variable for a specific purpose?

Being a developer who is still learning the ropes, I fail to understand the necessity of creating or retaining the express variable in an express/Node app. Instead of following this conventional approach: const express = require('express'); con ...

When you duplicate the React State object and make changes to the copied object, it directly affects

When attempting to duplicate a state object, I noticed that the state object is being modified directly in the code snippet below: @boundMethod private _onClickDeleteAttachment(attachmentName: string): void { console.log("_onClickDeleteAttachment | th ...

Encountering a Null Pointer Exception when executing the following script with Selenium WebDriver

public class TestBase { public static WebDriver driver = null; public static Properties prop = null; public TestBase() { try { prop = new Properties(); FileInputStream ip = new FileInputStr ...

Ways to retrieve a file from a specific location using fetch/axios?

For my research, I need to utilize certain network APIs such as fetch or axios to access a local file without using the fs module or importing them directly. I attempted to use both fetch and axios but found that they do not support fetching local files, ...

Tips for effortlessly enlarging an element

When you click on "#sidebarnav>li", the following happens: 1) The second child of it - <ul> element will expand and its class toggles between "collapse" and "collapse in". 2) "#sidebarnav>li" will receive the "active" class. 3) The "aria-ex ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...