kaushal
kaushal

Reputation: 815

Calling Javascript function from Android

I've an Android Webview project that needs to access some Javascript functions. I've set up everything as per this tutorial. And everything works, I can load html from Android app, can call Android class methods from Javascript as per the method described in the tutorial.

There's one thing which I can't make work and that is calling a Javascript function from Java class in Android. The Javascript function just prints a log message for test.

My index.html includes sample.js. Here's sample.js file:

(function () {
    'use strict';

    function init(event) {
       function foo(){
          console.log("javascript foo() function called from android");
       }
    }

    window.addEventListener('load', init, false);

}());

function foo1(){
   console.log("javascript foo1() function called from android");
}

And calling from Java Webview:

myWebView.loadUrl("javascript:foo1()"); //this works
myWebView.loadUrl("javascript:foo()");  //this gives error

As you notice, I've created 2 foo functions in Javascript files and they are placed differently. Calling foo1() works but calling foo() shows this error in logcat:

Uncaught ReferenceError: foo is not defined: Line 1 of file:///android_asset/index.html

I suspect that is because foo() is inside the anonymous function.

Can anyone show me how can I call foo() from Android?

Thanks.

Upvotes: 0

Views: 1278

Answers (1)

pavell
pavell

Reputation: 151

foo and foo1 functions have different scope. That's why foo is not available. To be able to call foo you can add this function to window object. See below:

(function () {
    'use strict';

    function init(event) {
       window.foo = function() {
          console.log("javascript foo() function called from android");
       }
    }

    window.addEventListener('load', init, false);

}());

function foo1(){
   console.log("javascript foo1() function called from android");
}

So foo function added directly to window object and it have the same scope as foo1.

Upvotes: 1

Related Questions