0

I cannot call a JavaScript method from Java!

I included this in the main java file:

 JavaScriptInterface jsInterface = new JavaScriptInterface(this);
        cordova_webview.getSettings().setJavaScriptEnabled(true);
        cordova_webview.addJavascriptInterface(jsInterface, "JSInterface");

@Override 
protected void onPause() { 
    super.onPause(); 
    cordova_webview.loadUrl("javascript:punish()");
    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?

2 Answers 2

1

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

window.fn = punish;

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

cordova_webview.loadUrl("javascript:window.fn()");

'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.

Sign up to request clarification or add additional context in comments.

Comments

0

Actually this is what made the difference and now it works fine: window.fn = punish in my JS code, and then call window.fn() from your android code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.