WebViewClient fails to execute on the second attempt

In my application, I have implemented a WebView to load local html content and then call a JavaScript function to scroll the WebView to a specific position. Here is how I achieve this functionality:

public class MyActivity extends Activity {

private WebView web1;
private int ID;
private MyWebViewClient webViewClient1;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);

        // Retrieve the ID of the content to be loaded.
        ID = getIntent().getIntExtra("element_id", 1);

        web1 = (WebView) findViewById(R.id.web1);
        web1.getSettings().setJavaScriptEnabled(true);

        // Initialize the webViewClients.
        webViewClient1 = new MyWebViewClient(true);

        web1.setWebViewClient(webViewClient1);

        displayArticle(web1);
    }

private void displayArticle (WebView wv) {

StringBuilder sb = new StringBuilder();

// Code for constructing the HTML String.

String finalHtml = sb.toString();

            wv.loadDataWithBaseURL("file:///android_asset/html/", finalHtml, "text/html", "UTF-8", null);

}

private class MyWebViewClient extends WebViewClient {
        String urlToLoad;

        MyWebViewClient (boolean setUrlToLoad) {
            if (setUrlToLoad) {
                setUrlToLoad();
            }           
        }

        public void setUrlToLoad () {
            this.urlToLoad = "javascript:(function () {" +
                    "var elem = document.getElementById('e"+ID+"');" +
                    "var x = 0;" +
                    "var y = 0;" +
                    "while (elem != null) {" +
                    "x += elem.offsetLeft;" +
                    "y += elem.offsetTop;" +
                    "elem = elem.offsetParent;" +
                    "}" +
                    "window.scrollTo(x, y);" +
                    "})()";
        }

        @Override 
        public void onPageStarted (WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            Log.d("Pages", "Page loading started");
        }

        @Override
        public void onReceivedError (WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            Log.d("Pages", "Webview content load error");
        }

        @Override
        public void onPageFinished (WebView view, String url) {
            super.onPageFinished(view, url);
            Log.d("Pages", "Page loading finished");

            if (urlToLoad != null) {
                // Scroll to the designated position.
                view.loadUrl(urlToLoad);
                urlToLoad = null;
            }
        }
    }
}

In the provided code snippet, after triggering the callback functions in the MyWebViewClient class using wv.loadDataWithBaseURL within the displayArticle(WebView wv) function, subsequent loadUrl calls do not elicit another round of callbacks from MyWebViewClient upon completion of the request in onPageFinished. This behavior persists even with other loadUrl invocations on the same WebView.

I am seeking insights into why this phenomenon occurs and would greatly appreciate any clarifications.

Answer №1

Calling loadUrl("javascript:...")
is unique in that it executes the JavaScript code within the context of the current page, similar to when using
<a href='javascript:...'>clicky</a>
, which means you will not receive callbacks for onPageStarted or onPageFinished.

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

Converting a three.js scene into SVG or alternative vector format for export

Can an SVG- or other vector-formatted image be exported from a scene rendered using three.js's WebGLRenderer? What about from a scene derived from CanvasRenderer? If not, how can one set up SVGRenderer with three.js? Creating a new THREE.SVGRenderer( ...

Stop phone vibration from interfering with accelerometer data on Android devices

Having developed an app that relies on accelerometer data to track movement and trigger phone vibrations based on specific thresholds, I encountered a major issue. The vibrations were causing interference with the accuracy of the accelerometer readings. A ...

React.renderComponent does not exist as a valid function

After reading several articles on ReactJs for beginners, I came across a tutorial that only provided code snippets. While attempting to work on my first component, I encountered some difficulties: Here is the full code: <!DOCTYPE html> <html lan ...

Encountering issues with establishing a MongoDB connection in Node.js 8

Nodejs : v8.11.3 - mongo : v3.6.3 Referencing the tutorial found at http://mongodb.github.io/node-mongodb-native/3.0/tutorials/crud/ app.js const mongoDB = require('./common_mongo.js') mongoDB.initMongo() common_mongo.js const MongoClient = ...

The function is not being triggered, should I include a window.load event?

Seeking to modify the CSS styles of an element upon click. ryan.js function ryanClicked(id){ document.getElementById(id).style.color = "blue"; alert("Asdsa"); } product.html <head> <script src="ryan.js"></script> </head ...

Show information upon opening

I am currently working on a project that involves 4 different divs, and I need the content of each div to be displayed based on dropdown selection. I found a code snippet that was close to what I needed, but after trying to adjust it, I haven't been a ...

Tips for adding an svg element to an existing svg using d3.js

Can another SVG be appended to an existing SVG parent using d3.js? I have tried using the 'svg:image' attribute, but unfortunately, I lose full control over the inner SVG child. The DOM node is created by d3, but it is not rendered, resulting i ...

Node.js used to create animated gif with unique background image

As I navigate my way through the world of node.js and tools like express and canvas, I acknowledge that there might be errors in my code and it may take me some time to grasp certain concepts or solutions. My current project involves customizing a variati ...

What kind of data structure is suitable for a MediaStream when passing it as a prop in a Vue component

Currently, I have set up a mediastream (multi WebRTC) and plan on placing each MediaStream into the child component that contains a video tag. The stream type is MediaStream, however there is no corresponding type for a Vue prop. Refer to the Vue documenta ...

What is the best way to refresh the DOM following an Ajax request using jQuery?

Is there a way to dynamically update the DOM with newly added records after making a call? Should I fetch the new database record content in the callback function and then append it using jQuery? Please provide guidance if there is insufficient data to a ...

The AbortController feature does not initiate the cancellation of an axios.get request

Currently, I'm experimenting with utilizing AbortController to cancel an API call. The axios library is being used for this particular call. Before integrating it into my project, I decided to test the cancellation procedure with a simple call: const ...

navigating between html pages using sliding next and previous buttons

I am in the process of developing a multi-page form spread across 4 different pages. I would like to incorporate next and previous buttons to allow users to easily navigate through the form. Although I have tried looking online for solutions, most results ...

Issue with Jquery AJAX success function specifically in Firefox browser, while other functions in the script are functioning correctly

I have 4 scripts using ajax, but one of them isn't functioning properly in Firefox. Even the alert in success doesn't trigger anything. There are no error messages, just nothing happening. However, it works perfectly fine in IE and Chrome. Belo ...

Managing various conditions in React is crucial for proper functionality

I am facing an issue with the if statement related to creating conditions based on the number of objects in an array. Specifically, I need the condition to be true if there are 2 objects in the array and false if there is only 1 object. These objects are s ...

NullPointerException when accessing Android ActionBar in a separate activity (API 19)

Within the primary activity, I have this code snippet: actionBar = getActionBar(); actionBar.setTitle("Title"); It functions as expected. However, in a secondary activity called from the initial one, I encounter an issue where calling getActionBar() to ...

Using a locally hosted HTML page to update a JSON file stored on my computer

In my current project, I need to reorganize data stored in an array named unknown. Each item in this array needs to be moved either to a new array called good or another one called bad. let data = { "bad":[], "unknown": ["b", "a", "d", "g", "o", ...

What is the best way to toggle a d3 svg overlay using a leaflet layer control?

I am looking for a solution to place 3 d3 svgs on a leaflet map and control them as easily as leaflet layers. Check out this code example, which works but is not ideal. The key part is from line 75 onwards, where I create a custom layer control linked to ...

Dynamic canvas feature

Struggling with making a rectangle element inside a responsive canvas? You're not alone. The challenge lies in ensuring the rectangle always occupies 100% of the canvas width while maintaining a static height of 50px. Canvas Markup <div id="newCa ...

Ensure that all resources have finished loading in the network tab before loading the CSS file

My goal is to ensure that every single file in the network tab of the devbar is loaded before loading my CSS file. I am using Gumroad's embedded product on my static website, and it is crucial for me to change the CSS only after everything has been lo ...

Issues with calculating SUM in MySQL within a Node.js Express application using EJS template

I am currently working on developing a dashboard for my Node.js project. The aim is to calculate the sum of certain values for an overview. While the SELECT statement works fine in my MySQL database, when I incorporate it into my Node project, I do not rec ...