如何获得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);
}
}
相关文章:
- 根据是否解析了 Promise 从函数返回值
- 从Ajax函数返回值
- 如何从嵌套的API函数返回值
- 从异步函数返回值
- 我如何才能继续'如果'语句来比较作为参数的多个函数返回值
- 从节点中的回调函数返回值
- 提交时不采用函数返回值.并且没有按预期行事
- 如何从工厂传递的函数返回值
- 为什么在循环中返回时函数返回值未定义
- 从JavaScript中的嵌套函数返回值
- 存在从函数返回值的问题
- 如何从setinterval函数返回值
- javascript:从匿名函数返回值
- angularjs从html调用函数返回值
- 从命名函数返回值
- 无法从Javascript中的嵌套函数返回值
- 这是显示javascript函数返回值的最佳方式吗
- 使用ajax和回调函数向函数传递值/从函数返回值
- 构造函数中的函数返回值
- 尝试从开关语句 -JS- 中的函数返回值