简体   繁体   中英

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

Is it possible in Android to call a JavaScript function (which is in my WebView) and get its return value in Java?

I know I can use a JavascriptInterface (in Android), for this I need to call the interface from the js function, but I can't modify the JavaScript function...

So I would like something like below, is it possible?

JavaScript:

function hello(){
    return "world";
}

Android:

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

Thank you

Yes, it is possible. I already do many javascript injection to people website before. You just need to inject your own javascript in any website.

For example

//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);

In WebAppInterface is where you create function to detect the javascript you inject earlier

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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