簡體   English   中英

如何獲取Android調用的JavaScript函數的返回值?

[英]How can I get the return value of a JavaScript function called by Android?

Android是否可以調用JavaScript函數(位於WebView中)並在Java中獲取其返回值?

我知道我可以使用JavascriptInterface(在Android中),為此,我需要從js函數調用該接口,但是我無法修改JavaScript函數...

所以我想要下面這樣的東西,有可能嗎?

JavaScript:

function hello(){
    return "world";
}

Android:

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

謝謝

對的,這是可能的。 我之前已經在人們網站上做了很多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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM