如何从webView,Android中的@JavascriptInterface方法调用Javascript? [英] How to call Javascript from @JavascriptInterface method in webView, Android?

查看:794
本文介绍了如何从webView,Android中的@JavascriptInterface方法调用Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的HTML网页代码:

Here is my HTML page codes:

<script>
    function native_callback() {
        alert("Test")
    }
</script>
<button onclick='native.appVersion()'>appVersion</button>

如您所见,只有一个按钮,当我点击按钮时,它会调用@JavascriptInterface方法 appVersion()。我想要做的是在 appVersion()方法中调用javascript函数 native_callback()。不幸的是,我会抓住一个java异常。

As you can see, there is only one button, and when I click the button, it will call the @JavascriptInterface method appVersion(). What I want to do is to call the javascript function native_callback() in the appVersion() method. Unfortunately, I will catch a java exception.

这是我的WebView类java源代码的一部分:

And Here is part of my java source codes of WebView class:

... // some other codes that not related

getSettings().setJavaScriptEnabled(true);
addJavascriptInterface(new InJavaScriptLocalObj(), "native");

... // some other codes that not related

final class InJavaScriptLocalObj {
@JavascriptInterface
    public void appVersion() {
        Log.i("JsInterface","Called!")
        loadUrl("javascript:native_callback()");
    }
}

而且,我可以从网页上捕获异常:

And, I can catch the exception from web page :

未捕获错误:在方法调用期间引发了Java异常 - 来自http:// my web page url的第6行

第6行是< button onclick ='native.appVersion()'> appVersion< / button>

BTW,鳕鱼 Log.i(JsInterface,Called!)已被调用,I可以看到日志。

BTW, the cods Log.i("JsInterface","Called!") has been called, I can see the log.

我该怎么办?

解决方案
实际上,它必须在另一个线程中调用,但与WebView对象相同。
这是我的代码:

Solution Actually, it's must be called in another thread but same as your WebView object. Here is my codes:

web_view.post(new Runnable() {
        @Override
        public void run() {
            web_view.loadUrl("javascript:native_callback()");
        }
    });


推荐答案

如何使用处理程序?
我检查它在我的项目中运行良好。

How about using handler ? I checked it works well in my project.

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        loadUrl("javascript:native_callback()");
    }
}, 0);

这篇关于如何从webView,Android中的@JavascriptInterface方法调用Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆