The behavior of Android webview varies when executing JavaScript code

I am currently involved in a project that involves reading user input via voice and displaying it on a website. I am able to read all input IDs on the site using Jsoup.

WebView webView = (WebView) findViewById(R.id.webview);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
            webView.clearCache(true);
            webView.clearHistory();
            webView.setWebChromeClient(new WebChromeClient());
            webView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    new ParseURl().execute(new String[]{url});
                }
            });

            webView.loadUrl(passed_site);

The method to read all input IDs is working perfectly fine.

private class ParseURl extends AsyncTask<String, Void, Boolean> {


        @Override
        protected Boolean doInBackground(String... params) {

            try {
                Document doc = Jsoup.connect(params[0]).get();
                Elements inputs = doc.select("input[type=text]");
                for (Element ele : inputs) {
                    listID.add(ele.attr("id"));
                }

            } catch (IOException e) {
                e.printStackTrace();


       }


                if(listID.size()>0){
                    return true;
                }
                return false;
            }

 @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            if(result){
                readMyVoice();
            }else {
                Toast.makeText(WebPage.this , "your site dont have input to fill" , Toast.LENGTH_LONG).show();
            }
        }
    }

If the site contains an input field, it will start writing to it by taking user input.

 private void readMyVoice() {
        Intent voicerecogize = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        voicerecogize.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
        voicerecogize.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        voicerecogize.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "ar-SA");
        startActivityForResult(voicerecogize, RESULT_SPEECH);
    }



 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RESULT_SPEECH && requestCode == RESULT_OK) ;
        {
            ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (results.size() > 0 ) {

                StartFillSiteForm(listID.get(count),results.get(0));
                count++;
                if(listID.size() == count){
                    return;
                }else{
                    readMyVoice();
                }
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }

However, there is an issue. Everything works fine until the method tries to write the user input to the website, at which point it opens a new empty page instead of filling in the input field as expected.

private void StartFillSiteForm(String id , String value){

        webView.loadUrl("javascript: document.getElementById('"+id+"').value='" + value + "';");

    }

The tested site is Google.

https://i.sstatic.net/ukOyU.png

Answer №1

It's recommended to activate javascript within an Android Activity

@SuppressLint("SetJavaScriptEnabled") 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylayout);
}

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

"Step-by-step guide on uploading a collection of photos to Firebase for seamless

Is there a way to efficiently store all user photos in a storage folder without generating a unique link for each photo? Instead, is it possible to create a single unique URL for the entire photos folder of the user? For example: Storage Photos Folder + ...

What steps can you take to prevent a potential crash from occurring when an unauthorized user attempts to access a page without logging in?

I've encountered an issue where the app crashes when trying to access a page that requires logging in. The reason for this crash is because the page attempts to load undefined data, resulting in the error: TypeError: Cannot read property 'firstN ...

Javascript and the output of Ajax request

I'm facing an issue with my JavaScript files interacting with the response from an ajax request. It seems that the JavaScript is unable to read the response from the ajax call. My question is, how can I get my jQuery plugin to access the classes in t ...

results vary when using both a while loop and callback

I'm having an issue with my while loop when filtering data from mongodb. Even though I should be getting three entries logged to the console, only one entry is making it to the callback function. Can anyone explain why this is happening? while(i--) { ...

Is there a specific plugin that enables dynamic calculations within a django formset?

Looking for a solution: Is there a jQuery plugin available that can perform calculations for a Django formset? The form is dynamic, changing the ID of each field per row whenever the add button is clicked. ...

Using JavaCV on android to implement facial recognition

My experience with the javacv face recognition library has been a bit inconsistent. While I can successfully recognize two static images, it seems to be doing so in a sporadic way. Sometimes it returns the correct result, but other times when using differe ...

Issue with iPhone CSS displaying differently on mobile devices

The CSS design does not display correctly on iPhone devices in real-life testing, even though it appears fine on browsers with mobile view emulators. Interestingly, the design also looks great on Android phones but encounters issues specifically on iPhones ...

What is the process for moving the final character to the beginning of a string?

Initially, the last letter in the string is being displayed. How can I rearrange it so that the last character appears first in the value? https://i.stack.imgur.com/uGq6H.jpg contentHtml += "<td rowspan1=\"" + 1 + "\" class=\"" + ( ...

Disabling the Bootstrap tooltip feature is a quick and easy process

Is there a way to turn off bootstrap tooltip on my website? I activated it with the code below: function activateTooltip() { const toolTips = document.querySelectorAll('.tooltip'); toolTips.forEach(t => { new bootstrap.Tooltip(t); } ...

The issue at hand is that one of the JavaScript buttons is functioning properly, while the other is not playing the video as intended. What steps can

I've been working on a script for my school project website that should make buttons play videos, but I'm running into an issue where it only works for the first button (btn). Programming isn't my strong suit, and I put this together based o ...

Is it possible to update the CSS file of an external SVG file in real-time?

Is there a way for an SVG image to reference another CSS file? A webpage contains an SVG file. A button allows users to switch between classic colors and high contrast mode on the entire webpage, including the SVG image. Attempt w.css (white backgrou ...

Place the div's scrollbar at the beginning of its content

Recently, I put together a custom CSS modal that includes a scrollable div (without the modal itself being scrollable). Interestingly enough, when I initially open the modal, the scrollbar of the div starts at the top as anticipated. However, if I scroll d ...

Various Utilizations through a Single Alexa Skill

In my skill SkillIntent, when asked about a specific game, it provides the description of that skill. Now, I want it to also inform WHO has that Skill when asked differently. Below is the code snippet: 'use strict'; var AlexaSkill = require(&a ...

Angular, choose, establish a default option

Despite my attempts, I am struggling to set the default option for a select element using AngularJS. My Technologies: AngularJS, Angular-UI-router, Bootstrap Key HTML snippet: <select ng-model="selectedCompany" ng-options="c.name for c in companies" ...

Troubleshooting Angular 2 with TypeScript: Issue with view not refreshing after variable is updated in response handler

I encountered a problem in my Angular 2 project using TypeScript that I could use some help with. I am making a request to an API and receiving a token successfully. In my response handler, I am checking for errors and displaying them to the user. Oddly en ...

The transition between backgrounds is malfunctioning

I want to create a smooth transition effect for changing the background of an element within a setInterval function. Currently, the background changes immediately, but I would like it to transition over a period of time. var act = true; setInterval(func ...

Tips for choosing a block using Puppeteer

Trying to retrieve the height of a series of blocks using Puppeteer, I encountered an issue where I couldn't select my block in page.evaluate() due to an error. The code snippet in question is as follows: (async () => { const browser = aw ...

Creating objects in separate JavaScript files and including them in the main file, along with their

Following the creation of a config.js file with an object named contextTokenObject, modifications and additions need to be made to this context object from another file (specifically when creating a passport strategy). In the 'passport.js' file, ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

Sending back numerous information in the catch block

Recently, I was testing out the fetch API and encountered an issue with logging a fetch error. I tried catching the error and logging it within the catch block. Strangely, even when I added additional console.log statements in the catch block, they would ...