Interacting with web content in an Android app using JavaScript and WebView

As a newcomer to the Android platform, I am working on creating an app using webview and JavaScript. However, when I try to run my code on a real device, I see nothing displayed on the screen. Any assistance or guidance on this issue would be greatly appreciated. Here is the code snippet that I have been working on:

public class MainActivity extends AppCompatActivity { WebView view_1,view_2; ImageView imageView;

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

    String url_1="<script type=\"text/javascript”  src=\"http://ds.claymcenter.com/embed.js\">\n" +
            "requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n" +
            "</script>\n" +
            " \n" +
            "<div id='ads'></div>";
    String url_2="https://paytm.com/";

    view_1 = (WebView) findViewById(R.id.webViewGoogle);
    view_2 = (WebView) findViewById(R.id.webViewFacebook);

    view_1.getSettings().setJavaScriptEnabled(true);
    view_1.loadData(url_1, "text/html", null);

    view_2.getSettings().setJavaScriptEnabled(true);
    view_2.loadUrl(url_2);

    imageView = (ImageView) findViewById(R.id.imageView);

    imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            view_1.reload();
            view_2.reload();

        }
    });
} }

Answer №1

Figuring out how to make things like this work can be a real challenge for me. I can't quite recall all the steps I took, but here are some suggestions:

To start off: Try enclosing that string in url_1 within

<html><body>...</body></html>
tags.

Next step: Consider using an "onDocumentReady" event to trigger your JavaScript once the JS file is fully loaded.

An alternative approach: Separate out the function call as shown below:

String url_1="<script type=\"text/javascript\”  src=\"http://ds.claymcenter.com/embed.js\">\n" +
        "</script>\n" +
        "<div id='ads'></div>";


String call = "javascript:requestAd('Rh8uGpcrlYMjXN1s', 'banner', 'ads', '320' , ‘50');\n"

After loading the HTML containing the JS file, you can utilize WebViewClient.onPageFinished() to determine when to execute the JavaScript call (keep in mind this is just a sample code snippet):

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {
            // TODO: Check URL after HTML with JS file loads
            if (urlMatches()) {
                view.loadData(call, "application/javascript", null); // MIME type might need adjustment
            }
        }
    });

This method acts similarly to "onDocumentReady," but it's done within the Java code.

You might encounter issues due to the statement in the loadData documentation:

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

As a final option, consider implementing loadDataWithBaseURL instead.

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

Creating an Array in AngularJS with ng-model and submitting it with jQuery: A comprehensive guide

I am struggling to submit an array of values using jQuery and AngularJS. Whenever I click the submit button, only the first array value is being retrieved. How can I get all array values using ng-model? Here is a link to all my code: https://jsfiddle.net/r ...

Navigating Users and Routing with Ionic Framework (AngularJS)

Currently, I am using Ionic for a new project and could use some guidance with routing (I'm relatively new to Angular). These are the states I have defined: $stateProvider.state('map', { url: '/map', views: { map: ...

Having trouble with jQuery functioning on mobile devices?

I'm experiencing an issue where this code works perfectly on my desktop, but not on my mobile device. I've tried using different browsers on my mobile, but the code still doesn't function. Any assistance would be greatly appreciated. var li ...

Error encountered due to circular structure in the data being posted in the

const formulaData = $(htmlContainer).find("ins").map(function (i, el) { return { fName: $(el).attr("data-record-name"), fID: $(el).attr("data-record-id"), fContent: $(el).text() } }); //keep if (for ...

React Native Router Flux encountered duplicate keys in two children

Version(s) react-native-router-flux v3.31.2 react-native v15.2.1 I am encountering an issue when trying to call Actions.dialog() multiple times and receiving an error message. Despite attempting the fix mentioned in https://github.com/aksonov/react-nat ...

Using AJAX to handle 404 errors in Slim PHP

When I attempt to retrieve data using AJAX in my Slim PHP application, I am encountering a 404 (Not found) error in the console. The specific error message is as follows: http://localhost:8888/Project/mods/public/edit-mod/ajax/get-categories?gameID=1 404 ...

Emulate a mouse click on an Angular element

I am facing a challenge where I need to execute Angular controller functions from outside of the application. Due to simplicity reasons, I am unable to make modifications directly to the Angular app itself. Ideally, the code should be able to run in the br ...

Having trouble locating a module in Angular2 and SystemJS while constructing a module loader

What's the Situation Here? Currently, I'm immersed in a project that involves SystemJS, Angular2, and @ngrx/store. My current focus is on developing a basic module loader. Here's how it works: I create a "module" in its own folder, named ...

Enhance the attributes of a collection of objects using values from a different array

Looking for a way to enhance a set of objects with properties sourced from another array? I have two arrays at hand. The first one contains a series of objects, while the second one consists of integers. My goal is to attribute a new property to each objec ...

unable to modify the content of a

I need assistance with a javascript function that dynamically creates panels using an ajax request. Once the request returns valid json data, I populate all the widgets as follows: function createAllWidgets() { var funcid = 'get_widget_info' ...

What steps can be taken to ensure a neutral value is returned in Mongodb aggregation when the specified attribute does not exist?

I need to create an aggregation that looks like this: Game.aggregate([{ $match: { "_id": { "$in": result.games } } ...

Android client encountering a connection rejection

I'm currently in the process of developing an android mobile client-server application that utilizes Socket for communication with the server. Everything runs smoothly when I test the application at home using my WIFI connection. However, the issue ar ...

Exploring touch interactions using D3.js and TUIO

I'm currently facing a challenge with implementing multi-touch functionality and the d3.slider in my D3 Map. You can see the current state of my project in this video. With the d3 slider, I can spawn points and navigate around the map using touch even ...

Switch up the query parameter in the current Vue router route

I am working on appending attribute parameters to a URL using the following code snippet: this.$router.push({ query: Object.assign({}, this.$route.query, { attributes: this.encodedAttributes() }) }); However, I have noticed that when I call this method fo ...

Issue with Three.js Shader rendering improperly on a specific custom geometry mesh surface

I am facing a challenge with applying a shader to a single face Mesh in Three.js. Upon applying the shader material to the mesh, it seems to only read a single pixel of the shader and apply that value to the entire face. I have tested this using the follo ...

I've noticed that the NextJs router appears to be significantly slower in comparison to React

I currently have a website that is built in both React Js and Next Js. The issue I am currently encountering is that the router in NextJs is noticeably slower compared to react-router-dom. It takes almost 2-3 seconds to change the route. To experience th ...

Attempting to iterate through and retrieve the names listed in the table

I have a code that I need help with in extracting names from td elements using jQuery. In certain instances, if the td is empty, I want to merge the left-side td with the 5 right-side tds because the first td on the right side is empty and the second td c ...

JavaScript/jQuery not working on website using WordPress and PHP

Currently, I am tackling an issue on a website . It seems that every time I try to incorporate any jQuery element or plugin on top of the standard JS functionality of the site, there is a problem. For example, should ideally function as a dynamic content ...

AngularJS: Unable to preserve the data

I'm currently working on an issue with saving updated functions using angularJS. I've managed to edit the data and update it on the database side, but the changes aren't reflecting on the frontend side unless I logout and login again. I need ...

Exploring the concept of inheritance and nested views within AngularJS

I've encountered a challenge while setting up nested views in AngularJS. Utilizing the ui-router library has been beneficial, but I'm facing issues with separate controllers for each view without proper inheritance between them. This results in h ...