Cannot call javascript methods from java


I cannot call a JavaScript method from Java!

I included this in the main java file:

 JavaScriptInterface jsInterface  new JavaScriptInterface(this);
        cordova_webview.addJavascriptInterface(jsInterface, "JSInterface");

protected void onPause() { 
    Log.d(TAG, "onPause");

BUT I get this error in logacat:

07-15 17:25:18.490: D/CORDOVA_ACTIVITY(6422): onPause
07-15 17:25:18.495: D/CordovaLog(6422): null: Line 1 : Uncaught ReferenceError: punish is not defined
07-15 17:25:18.495: E/Web Console(6422): Uncaught ReferenceError: punish is not defined at null:1

the method is in index.js, which is included in the html.

However I tried to include the method in the html through a <script> tag and it’s executing, but only after onResume!

How can I solve this?


You could try this, in your javascript code, set:

window.fn  punish;

and then call window.fn() from your android code:


‘fn’ is not special here. We are just trying to make your function visible or accessible. ‘window’ object is already accessible, so we just set a reference to your function there. So, for example,

window.myFunc1  punish;

.. would be fine too. I’m not entirely sure why this is required, but I’m posting this here anyway.

Answered By – radical

Leave a Comment