【问题标题】:How can I get the return value of a JavaScript function called by Android?如何获取 Android 调用的 JavaScript 函数的返回值?
【发布时间】:2016-10-25 14:58:22
【问题描述】:

是否可以在 Android 中调用 JavaScript 函数(在我的 WebView 中)并在 Java 中获取其返回值?

我知道我可以使用 JavascriptInterface(在 Android 中),为此我需要从 js 函数调用接口,但我无法修改 JavaScript 函数...

所以我想要像下面这样的东西,可以吗?

JavaScript:

function hello(){
    return "world";
}

安卓:

String res = myWebView.loadUrl("javascript:hello()"); 
// res = "world"

谢谢

【问题讨论】:

    标签: javascript android webview


    【解决方案1】:

    是的,这是可能的。我之前已经对人们的网站做了很多 javascript 注入。您只需要在任何网站中注入您自己的 javascript。

    例如

    //simple javascript to pass value from javascript to native app
    String javascript =  "javascript:function testHello(){return Android.hello('HAI'); testHello();}"
    
    webview.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    super.onPageStarted(view, url, favicon);
                }
    
                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    //put your function in string and load the javascript when the page is finished load
                    view.loadUrl(javascript);
                }
    });
    
    // 'Android' is your variable key for triggering the function ex: Android.hello(), Android.calculate()
    // you can change to other name like 'APP', so in javascript be like this ex: APP.hello(), APP.calculate()
    
    webview.addJavascriptInterface(new WebAppInterface(this), "Android");
    
    //load website
    webview.loadUrl(PageUrl);
    

    在 WebAppInterface 中,您可以创建函数来检测您之前注入的 javascript

    public class WebAppInterface {
        Activity mContext;
    
        public WebAppInterface(Activity c) {
            mContext = c;
        }
    
        //this function will get your value from the javascript earlier.
        //Android.hello('value')
    
        @JavascriptInterface
        public void hello(String value){
            //you will get HAI message in here
            Log.i("TAG",value);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2013-04-01
      相关资源
      最近更新 更多