首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取Android调用的JavaScript函数的返回值?

问如何获取Android调用的JavaScript函数的返回值?
EN

Stack Overflow用户
提问于 2016-10-25 22:58:23
回答 1查看 1.8K关注 0票数 0

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

我知道我可以使用JavascriptInterface (在安卓系统中),为此我需要从js函数调用接口,但我不能修改JavaScript函数……

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

JavaScript:

代码语言:javascript
复制
function hello(){
    return "world";
}

Android:

代码语言:javascript
复制
String res = myWebView.loadUrl("javascript:hello()"); 
// res = "world"

谢谢

EN

回答 1

Stack Overflow用户

发布于 2016-10-26 12:48:55

是的,这是可能的。我之前已经在人们网站上做了很多javascript注入。你只需要在任何网站上注入你自己的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

代码语言: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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40243307

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档