Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a javascript function directly from an activity in Android?

I wanted to know if there is any way that I can call a JavaScript function from native Android Activity.

I came across:

webView.loadUrl("javascript:hello()");

But it did not work for me.

Also, how will Android know in which html page does this JavaScript function reside?

like image 711
Smitha Avatar asked Dec 28 '11 10:12

Smitha


People also ask

How do you call a JS function when a button is clicked?

JavaScript – Call Function on Button Click Get the reference to the button. For example, using getElementById() method. Call addEventListener() function on the button with the “click” action and function passed as arguments.

How do you call a JavaScript function from another file in HTML?

The first method is to call the JavaScript function in HTML. For this, you have to create a function then define this function either in the head section or body section of the HTML document. You can either create a link or a button and then an onclick() event is associated with them in order to call this function.


1 Answers

In case anyone has any issues with this like I did, you need to call your javascript function after the page has finished loading otherwise the javascript won't be called:

    webviewer.loadUrl("file:///android_asset/mypage.html");
    webviewer.setWebViewClient(new WebViewClient() {

        public void onPageFinished(WebView view, String url)
        {
            webviewer.loadUrl("javascript:hello()");
        }
    });
like image 182
tim.paetz Avatar answered Nov 15 '22 18:11

tim.paetz