Using Angular to Dynamically Change Webview URLs

I've been attempting to update the URL of my webview by invoking a function with AngularJs, but unfortunately, I haven't been successful.

Below is my Angular class:

app.controller("speechController", function($scope){
    $scope.page = 'index.html';
    $scope.url = function(page){
        Android.receivePage();
    }
});

And here is my Java class:

public class MainActivity extends AppCompatActivity {


    Button b;
    CustomWebViewClient customWebViewClient;
    WebView myWebView;
    private TextToSpeech tts;
    private final int REQ_CODE_SPEECH_INPUT = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);



        myWebView = (WebView) findViewById(R.id.webView);
        myWebView.addJavascriptInterface(this, "Android");
        myWebView.setWebViewClient(new WebViewClient());
        WebSettings webSettings = myWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_asset/index.html");
        b= (Button)  findViewById(R.id.button);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                receivePage();

            }
        });

    }



    @JavascriptInterface
    public void receivePage() {
        myWebView.loadUrl("file:///android_asset/index.html");
    }
}

It's worth noting that I included a button in onCreate to test the receivePage function. Through debugging, I observed that both the Angular function and the button onClick function successfully call receivePage(), but only the button correctly updates the URL. It is crucial for my project to use Angular to modify the webview. Can anyone provide insight into why my code is behaving in this manner?

Answer №1

After solving the issue, I wanted to share my solution for others facing the same problem. The JavascriptInterface operates on a different thread than the webview, and the webview only accepts requests from the same thread. To resolve this, I simply needed to make the following adjustment:

@JavascriptInterface
public void receivePage() {
    myWebView.loadUrl("file:///android_asset/index.html");
}

I replaced it with:

@JavascriptInterface
public void receivePage() {
    myWebView.post(new Runnable() {
        @Override
        public void run() {
            myWebView.loadUrl("file:///android_asset/index.html");
        }
    });
}

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

Every time I attempt to log in, the code keeps generating an error message net::ERR_EMPTY_RESPONSE. If successful, it should redirect to the

The code is producing a net::ERR_EMPTY_RESPONSE error when attempting to log in. The username and password are hardcoded. I simply want the admin to input their credentials on the Employee.html page, and if they match the ones in the main.js file, redirec ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

vue.js libs requiring "new ..." are being scolded by eslint for their misspelling

When working with Vue libraries, such as Swiper, that require the use of 'new …' in the script section, I encounter ESlint errors no matter how I try to write it. Even though 'new ...' works perfectly fine in the frontend, ESlint cont ...

What are the steps for creating a standalone build in nextJS?

Currently, I am undertaking a project in which nextJS was chosen as the client-side tool. However, I am interested in deploying the client as static code on another platform. Upon generating a build, a folder with all the proprietary server elements of ne ...

What is the process for implementing a splash screen in VueJS?

Having trouble creating a splash screen (loading-screen) in Vue JS that fades away after a few seconds to reveal the default view? I've experimented with several approaches, but none seem to be working for me. The closest example I found is on CodePen ...

Exploring the translation of Java Guava's sets.difference function into Go programming language

Exploring Java Guava's Sets.difference function: Known = ["v1","v2"]; Incoming = ["v2","v3","v4"] incoming = ["v2","v3","v4"]; knownUpdated = ["v2"] Sets.difference(Known, Incoming) = v1 (To be removed) Sets.difference(incoming, knownUpdated) = v3 ...

Is there a way to programmatically click on a link within the first [td] element based on the status of the last [td] element in the same [tr] using codeceptjs/javascript?

The anticipated outcome: Pick a random assignment from the table that has the status "Not start". Below is the table provided: <table id="table1"> <tbody> <tr class="odd1"> <td> < ...

Is there a way to keep the modal window open in React without it automatically closing?

I have been working on a modal window implementation in React. I defined a state variable called modalbool to control the visibility of the modal window. The modal window is displayed only when modalbool is set to true. Additionally, I created a parent com ...

Kendo Template Function: Angular JS version 1.6

I'm working with a currency column that looks like this: { field: 'INVOICE_AMOUNT_ORIGINAL', title: $translate.instant('invoiceAmount'), format: '{0:n}', template: '#= currency(dataItem.INVOICE_AMOUNT_ORIGIN ...

Employing AJAX to send form data to a pair of destinations

Can anyone help me out? I am having trouble using AJAX to submit my form to one location and then to another. Once it's posted to the second location, I want it to send an email with PHP to a specified recipient, but for some reason, it's not wor ...

Combining various variables in Java

Hello, I'm new to Java and struggling to make this code snippet work because I can't seem to concatenate the variables properly. public class Fish { public static void main(String args[]){ String species = "Barracuda"; St ...

Introducing React JSX via a nifty bookmarklet

Looking to convert code found in an HTML file into a bookmarklet? Here's the code snippets involved: <script src="JSXTransformer-0.13.3.js"></script> <script src="react-0.13.3.js"></script> <script type="text/jsx;harmony=tr ...

Connect various models together, or create synchronized computed properties

At times, the model abstraction may fall short, leading to the necessity of synchronizing two different models. For instance, I have two lists linked by an angular sortable, which requires a model structure like this: left = [{name:"one"}, {name:"two"}]; ...

Creating multiple nested ng-repeats in an AngularJS table

Managing a large amount of data on users' availability by hour for multiple days can be challenging. The data is structured as follows: availData = { "date1":arrayOfUsers, "date2":arrayOfUsers, ... } arrayOfUsers= [ userArray, userArray, ... ] user ...

Switching <div></div> to inline-block doesn't seem to have any effect (repl.it provided)

Could someone assist me with changing the div element to an inline block? I've been having trouble with it. For reference, here is my repl.it: https://repl.it/repls/AwareContentTechnician ...

The value does not get refreshed in AngularJS

I'm facing an issue with Angular Material where the current set of chips is not being updated correctly. Even after removing a chip, the array list of current chips still shows the removed chip when I try to use it. After calling $scope.remove to rem ...

Implementing Object.somefunction() in ngFor with Angular

In my Angular project, I am using an ngFor loop to iterate over keys generated by Object.keys() in the following code snippet: <ul id='nav-tablist' class='tabrows'> <li *ngFor="let tab of obj.keys(tabList)"> ...

How can I prevent AngularJS from re-rendering templates and controllers when navigating to a route with the same data?

Is it possible to prevent the templates for the controllers of a route from re-rendering when changing the route, even if the data remains unchanged? ...

Ways to make a jsonp request without including the 'callback' in the URL

I've been working on retrieving information from an Icecast Radio station using their API, which offers the status-json.xsl endpoint to access this data. Despite the format being in xsl, I suspect it returns a JSON file. However, I've encountere ...

What is the method for setting the current time as the default in a time picker?

Below is a snippet of code where I attempt to implement a date picker and set the current time as the default value. .HTML <input type="time" [(ngModel)]="time"> .TS time; constructor() { this.time= new Date(); } ...