简体   繁体   English

无法从Java调用javascript方法

[英]Cannot call javascript methods from java

I cannot call a JavaScript method from Java! 我无法从Java调用JavaScript方法!

I included this in the main java file: 我将其包含在主java文件中:

 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: 但是我在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. 该方法位于html中包含的index.js中。

However I tried to include the method in the html through a <script> tag and it's executing, but only after onResume! 但是,我试图通过<script>标记将方法包含在html中,并且该方法正在执行,但仅在onResume之后!

How can I solve this? 我该如何解决?

You could try this, in your javascript code, set: 您可以在javascript代码中尝试设置:

window.fn = punish;

and then call window.fn() from your android code: 然后从您的Android代码中调用window.fn():

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

'fn' is not special here. “ fn”在这里并不特殊。 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. 我不确定为什么要这样做,但是无论如何我还是在这里发布。

实际上,这就是与众不同的原因,现在它可以正常工作:window.fn =用我的JS代码惩罚,然后从您的android代码中调用window.fn()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM