Using JavaScript functions within a WebView and ViewPager

Encountering an issue with Javascript in WebView. I have a ViewPager that dynamically adds Views as needed. Prior to adding a View to the viewpager, I inflate it and load an embedded webview inside:

 LayoutInflater inflater = this.getLayoutInflater();
        FrameLayout v = (FrameLayout) inflater.inflate(R.layout.notebook_page, null);
        setupWebView(v);
        pagerAdapter.addView(v);
        pagerAdapter.notifyDataSetChanged();

Within the webview, initially load a local html file, then inject a JS function to set various inputs on the HTML.

    private void setupWebView(View v) {

    myWebView = (WebView) v.findViewById(R.id.webview);
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl("file:///android_asset/web_resources/index.html");
    myWebView.setWebViewClient(new WebViewClient() {
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(myWebView, url);
            Log.d("WebView Content", "Injecting JS");
            myWebView.loadUrl("javascript:function('" + input_var + "')");
        }
    });
}

The setupWebView function is being called correctly for each inflated view, but the JS function isn't functioning properly.

This code works flawlessly in an Activity when there's only 1 page. However, within ViewPager where multiple pages display webviews, the JS only loads on the last page.

Any suggestions or recommendations would be greatly appreciated?

Answer №1

To effectively utilize JavaScript on Android 5.0, a different approach is needed. The following code snippet demonstrates how to achieve this:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.evaluateJavascript("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.e("LoginActivity onReceiveValue", s);
                    }
                });
            } else
                webView.postUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');", null);

Furthermore, remember to add the @JavascriptInterface tag to your JavaScript method as shown below:

@SuppressWarnings("unused")
@JavascriptInterface
public void processHTML(final String html) {
//method called from javascript
}

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

What causes the error of androidx.collection.SparseArrayCompat.size() being thrown on a null object reference?

I encountered this exception in my application when attempting to move it into the background. java.lang.NullPointerException: Attempt to invoke virtual method 'int androidx.collection.SparseArrayCompat.size()' on a null object reference at ...

Avoiding memory leaks in Node.js with Express framework

Dealing with memory leaks in nodejs (express.js) has been a challenge for me. I followed various tutorials online, but unlike the examples provided, identifying the source of the leak in my code has not been straightforward. Through the use of Chrome Dev T ...

Display HTML in JavaScript without altering the Document Object Model

Is it possible to style a custom HTML tag called "location" without directly modifying the DOM? For instance, having <location loc-id="14" address="blah" zipcode="14" /> Would it be feasible to render it like this: <div class="location"> ...

Factors to take into account when determining the level of effort needed to transfer an application to a different device

Having experience with a G1 and an HTC Hero handset, I have mainly tested my applications on these devices. However, with the introduction of new SDKs and Android handsets that come with different screen resolutions, densities, and capabilities like Droid, ...

jquery sequential fade effect

I am trying to make each div fade in one by one. Visit this link for reference <div id="w"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div> $(function() { $(&a ...

numerous sections within a solitary webpage

I need to implement multiple tabs on a single page, how do I modify the code to make this possible? Take a look at the codepen for reference. Here is the jquery code I have written so far: var tabs = $(".tabContainer ul li a"); $(".tabConten ...

There was an issue converting the string into a JSON object

I am attempting to retrieve data from a MySQL database to an Android application. In the code snippet below, the output is displayed on the logcat using 'tagconvertstr'. However, I am encountering an error stating that the string cannot be conver ...

Tips for creating a function to deactivate all other buttons

I'm currently developing a trivia game where users select answers from buttons. I want to create a function that will disable the other answer buttons once a user has tapped on one as their answer. Currently, if a user taps multiple buttons in success ...

Utilizing Jquery Validation to Remove a Class Upon Form Validation Success

In my current registration process, I have a multipart form where each subsequent form is displayed when the next button is pressed without fading effects. Initially, the button appears faded. Here's a simplified version of how I handle the first form ...

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

Having trouble activating the submit function using an external JavaScript file

Having trouble getting the form to submit properly. I have placed the form inside a <div id="access"></div> by setting its innerHTML using an included js file in the header of the page. Here's how it looks: <div id="access"> < ...

FusionMaps XT integration with VueJs: Troubleshooting connectorClick events issue

I am experiencing some issues with events connectorClick on my VueJS processed map. When I click on the connector line in the example below, the alert function does not seem to work as expected. Vue.use(VueFusionCharts, FusionCharts); let grphMap = new ...

When a button in a React list is clicked, the event always returns a reference to the last element

I am facing an issue with retrieving the selected item from an array of elements. I have an API service that returns a list of 5 jobs, and a React page to display the applicants. The table rendered from the list has a menu button for each row. When I click ...

Vue router is unable to verify the user's authentication

I have certain app routes that are supposed to be restricted to admins only. I've added requiresAdmin: true, to the meta of those routes, but for some reason it doesn't prevent other users from accessing them. Code Note: I've included comme ...

Changing up the content within a jQuery class

I have 10 <p> tags in my HTML with the class of .rule I am looking to update the text for each of them independently without resorting to individual IDs like #rule1, #rule2, #rule3: $('.rule').eq(0).text('Rule 1') $('.rule& ...

A guide to programmatically downloading a file with JavaScript on Internet Explorer

I'm currently facing a challenge with my web page. There is a button that, when clicked, should generate a CSV file (by converting from JSON) for the user to download. I've implemented the logic based on this jsfiddle, and it works perfectly in C ...

Testing a React component using the `ua-parser-js` plugin with Jest and React Testing Library

I've developed a simple component that displays an image depending on the operating system you are using (in this case, iOS and Android). import { UAParser } from "ua-parser-js"; export const DownloadApp = ({ appleStoreUrl, playStoreUrl }: ...

Execute Babel task individually for each file instead of running it on the entire directory, Grunt

I've set up a Grunfile to monitor .js files in the src/ directory and trigger the babel task from https://github.com/babel/grunt-babel to generate ES5 files in the dist/ directory: module.exports = function(grunt) { require('load-grunt-task ...

Passing data between child components using Vuejs 3.2 for seamless communication within the application

In my chess application, I have a total of 3 components: 1 parent component and 2 child components. The first child component, called Board, is responsible for updating the move and FEN (chess notation). const emit = defineEmits(['fen', 'm ...