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

Comparing "if" and "else" within the XMLHttpRequest() function will not

function banUser() { var userToBan = document.getElementById('userToBan').value; var cid = document.getElementById('chatId').value; if (userToBan.length <= 0) { var x = document.getElementById("banerror"); x.innerHTML ...

determine if the req.params parameter is void on an express route

Hi everyone, I'm a beginner with node and express and could really use some guidance. I am currently attempting to create a get request that checks if the req.params.address_line is empty, and then performs an action based on that condition. However, ...

How to upload an image using Java and store it on a server without the use of Html5

Looking to upload an image file on the server using a servlet without utilizing HTML5. While browsing through stackoverflow, most answers I found were based on PHP. I attempted to read the image file at the client-side in JavaScript with FileReader.readAsD ...

Is it possible to disable the timeout for a single call using Axios?

I have set up an axios client instance in my application like this: const backendClient = axios.create({ baseURL: window['getConfig']?.url?.backend, httpsAgent: new https.Agent({ rejectUnauthorized: false }), timeout: window['getConfig ...

Navigate using React to a different HTML page based on certain conditions

After calling the fetch function, I am able to retrieve the correct token from the backend application. However, every time in this program, even if an incorrect token is retrieved, the program still navigates to StudentLobby (this should only happen when ...

Revisiting Dynamic URL Parameters with React Router and Express

After setting up my React router to navigate '/Article/1/' via a link, everything seems to be working fine. However, I encountered an issue when refreshing the browser as it no longer detects my Article component. MainApp.js import React from & ...

Using Selenium to interact with drop-down lists using div tags instead of select tags

As a newcomer to automated testing using Selenium Web Driver, I am struggling to test drop down lists for the location type without relying on the select command. The element in question is enclosed within a div tag. I attempted sending keys but that meth ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Hovering into Transition Time

My article card has a transition on the top attribute of the info div, which is supposed to be smooth and last for 0.3 seconds. However, the description suddenly appears during this transition. I'm trying to figure out why this is happening and how to ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: with this new link: without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restriction of needing at least 10 reputation points in order to post more t ...

Issue with downloading files in Internet Explorer is not functioning properly

I am encountering an issue in my Angular.js controller where downloading a CSV file works perfectly in Chrome but not in IE. The browser console log indicates: HTML7007: One or more blob URLs were revoked by closing the blob for which they were create ...

Timing intervals are not supported by Android handlers

I'm in the process of developing an Android app that requires short vibrations at specific intervals under certain conditions. However, I've encountered a problem where the device sometimes vibrates for longer than intended or continues vibrating ...

Is there a different option instead of relying on promises for asynchronous requests?

Let's consider a scenario where we have a basic front end application (perhaps using Angular) and a back end app. When the front end app performs a get request, in most cases, the Angular repository will initiate an $http.get request which will return ...

Enhancing the efficiency of JavaScript code

Imagine you have a web application processing 1,000,000 user logins per hour. and the code below is executed during each user login: if (DevMode) { // make an Ajax call } else if (RealMode) { // make another Ajax call } else { // Do something ...

Innovative react route

Currently, I am in the process of learning about dynamic react routes. In the code example I am working on, there are different buttons for each task. The goal is to render the WorkDetails component when a button is clicked. However, it seems to not be fun ...

Telegram: verification key mismatch detected

I am currently facing an issue with implementing a Telegram PHP example using JavaScript. The hashes do not match, even after running the example's php code which also resulted in failure with identical hashes. I have tried adjusting my bot settings b ...

Styling is lost in FancyBox popup when loading Partial View

I've been attempting to incorporate a partial view into my MVC project using fancybox. It seems to be loading the content correctly, mostly anyway, as it tends to cut off part of the page and loses all styling from the view upon loading. Even after i ...

What is the best way to translate an integer from a String and interpret it identically?

I have a task of processing a file that contains both strings and integers. An example representation of the file is shown below: File.txt This is 1234 This is 2568 My goal is to perform subtraction on the numbers found in two consecutive lines. I am u ...

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

The Bizarre getString Glitch

My current problem revolves around a particular class that is meant to return a string. Here is the code snippet: package TextRPG; public class File { static String file; public static void setFile(String fileLocation) { file = fileLoca ...