Retrieve the image source from a webview on an Android device

As I attempt to retrieve the source of a captcha image from a webview, I encounter an error message when running the below code:

Uncaught TypeError: Cannot read property 'src' of null

Furthermore, if I successfully obtain the image src, how can I display the image in an image view?

Any assistance on this matter would be greatly appreciated.

Here is the current state of my code:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv = (WebView) findViewById(R.id.wv);
    mImgCaptcha = (ImageView) findViewById(R.id.imgCaptcha);
    done = (Button) findViewById(R.id.done);
    contentView = (TextView) findViewById(R.id.textView);
    username = (EditText) findViewById(R.id.editText);
    password = (EditText) findViewById(R.id.password);
    code = (EditText) findViewById(R.id.code);

    WebSettings webSettings = wv.getSettings();
    webSettings.setJavaScriptEnabled(true);
    wv.getSettings().setDomStorageEnabled(true);
    wv.loadUrl("https://noor.moe.gov.sa/NOOR/Login.aspx");

    wv.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
    System.out.println(wv.getUrl());

    done.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            wv.loadUrl("javascript:var x = document.getElementById('tbPublic').value = '" + username.getText().toString() + "';");
            wv.loadUrl("javascript:var x = document.getElementById('tbPrivate').value = '" + password.getText().toString() + "';");
            wv.loadUrl("javascript:var x = document.getElementById('tbCaptcha').value = '" + code.getText().toString() + "';");
            
            try {
                Thread.sleep(2000);
                wv.loadUrl("javascript:(function(){" +
                        "l=document.getElementById('btnLogin');" +
                        "e=document.createEvent('HTMLEvents');" +
                        "e.initEvent('click',true,true);" +
                        " l.dispatchEvent(e);" +
                        "})()");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

Answer №1

One reason you may encounter issues when trying to query the DOM is because the page hasn't fully loaded yet. To ensure successful DOM querying, it's essential to wait until the page has completely loaded.

To address this issue, set a WebViewClient for the webview and listen for the onPageFinished event. An example code snippet can be seen below:

webView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);

        // Now it's safe to query the DOM.
        webView.loadUrl("javascript:var a = document.getElementById('imgCaptcha').src;");
    }
});

For more information, check out: https://developer.android.com/reference/android/webkit/WebViewClient#onPageFinished(android.webkit.WebView,%2520java.lang.String)

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

Discovering dependencies for the Tabulator library can be achieved by following these

Can anyone provide me with a complete list of dependencies for Tabulator 4.2? I have already reviewed the package.json file, but it only contains devDependencies. ...

Jest identifies an open handle when working with an Express application

For quite some time now, I've been grappling with a particular issue. It all started when I was conducting basic integration tests using a MongoDB database. However, I've minimized the code to its simplest form. The only thing left running is a s ...

Passing an array from PHP to JavaScript using AJAX

Here is the code snippet on the server side: <?php header('Content-Type: text/html; charset=utf-8'); require "../general.variables.php"; require "../functions_validation.php"; require "../functions_general.php"; require "../../db_con.php"; $ ...

Navigate to the bottom of a Vue modal window by scrolling down

I am facing an issue with implementing a Vue calendar inside a modal. When the calendar appears, I want the window to automatically scroll to the bottom, but I am having trouble making it work. Unfortunately, I can't provide the code for the whole mod ...

Is there a way to specifically retrieve the number of likes or followers from Facebook, Twitter, Instagram, and Snapchat in order to display them on my HTML website?

Can you provide guidance on how to obtain the total numbers of likes or followers for our Facebook, Twitter, Instagram, and Snapchat pages without including the plugin boxes or buttons? We are solely interested in the actual numbers. Would this be feasibl ...

Selenium gets caught in endless loops

On my homepage, I have a variety of links that lead to different applications. Each link opens a new tab or window, where I need to check for the presence of a specific element using its XPath (which is provided from an Excel file for all applications). ...

I am experiencing difficulty with the color of my progress bar in Firefox

After successfully creating an interactive progress bar that works perfectly in Google Chrome and surprisingly also in Safari without vendor prefixes, I encountered a roadblock when testing it on Firefox. The progress bar color reverts back to the default ...

What is the best way to show an image from a website within a JOptionPane?

When utilizing selenium to perform webpage testing, I am interested in showcasing an image sourced from the page on a JOption pane. What steps can be taken to achieve this? Below is the relevant code snippet: WebDriver driver = new FirefoxDriver() ; dri ...

Are React lifecycle methods failing to execute? Is there a workaround to ensure lifecycle methods are properly triggered?

Today I stumbled upon something unexpected. It's not a common occurrence in Angular or any other JavaScript library or framework. I was surprised when the React lifecycle methods didn't trigger. Is there some kind of hack behind it? Let's ta ...

What is the reason that the attr function fails to function in this particular scenario?

I want to implement a functionality where clicking on an input field clears its value, but I can't seem to make it work. Here is the HTML code: <input id='input' type="text" name="phppostvar" value="clear this"></input> This i ...

"Can you provide guidance on the correct way to structure a string in JSON

I am dealing with a JSON file that has been parsed using Java functions and stored in a database. One particular attribute within the JSON contains multiple lines and needs to be properly formatted. Currently, I am using "\n" and "\t" to format t ...

What is the method to reach the DOM element of a different component in Angular?

My application is structured as follows: <nav></nav> <router-outlet></router-outlet> <footer></footer> Within the router-outlet, I have various components depending on the route. On some of these pages, I need to acces ...

v-bind is not recognizing modifications in the array elements (vue js)

I'm currently working on switching the id of an image upon the user clicking a button. At first, the id should be set to B0_h, but once the user clicks the button, it should trigger a change in an array value to true. Initially, all values in the arra ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

Utilizing TaskRouter in Django: Setting Up Twilio Workers for Handling Incoming Calls

Currently, I am in the process of developing a straightforward contact center application with Django and incorporating technologies such as Twilio, TaskRouter, and Client JS SDK. To keep track of the call log for each client, I am utilizing the status_ca ...

Android device unable to establish connection with Socket.io server

Attempting to establish a connection between an Android app and a Socket.io server on the MEAN Stack. Emitting a test string on the socketTesting channel and listening on the server side. MainActivity.java public class MainActivity extends ActionBarActi ...

Is it possible to display or hide a spinner within a span using Javascript and AJAX?

When submitting a contact form, I want to display and hide a spinner on the submit button. The spinner should be visible while the form is being submitted and hidden once the submission is complete. Below is the code for my submit button with the spinner: ...

Guide to creating 2D point shapes with three.js

Is there a way to render a 2D shape of points in three.js? I have been struggling to find a working geometry for this task. I simply want to create a polygon of points that lie on the same plane. The 'Shape' object doesn't seem to be suitab ...

Exception thrown while converting a string in the format 2018-11-26T15:12:03.000-0800 to a Java LocalDateTime in the format 'M/dd/yy HH:mm:ss a z'

I created a utility function to convert a string time value in the format 2018-11-26T15:12:03.000-0800 to localdatetime with the format "M/dd/yy HH:mm:ss a z". However, when trying to convert a string in the format 2018-11-26T15:12:03.000-0800 to java.tim ...

What is the best way to determine the amount of alphabetical characters in a given String?

I am currently faced with a straightforward challenge: How can I count the number of alphabetic characters in a given string str? My current approach looks something like this: int letterCount = 0; for(int i = 0 : str){ String check = "" + str.charAt ...