2015-02-12 12 views
0

的js代碼: 功能(){回報 「你好」;}Android的webview活動,如何讓js返回值?

android的web視圖活動

,如何調用JS函數A()得到返回值 「你好」?

webview.addJavaInterface? webview.loadUrl()?我無法得到它。

請告訴我如何解決問題。

回答

0

我的建議是:

1-定義JavaScript接口

一個普通的Java類的一些方法和屬性,使用批註來公開你的願望web視圖JS範圍的方法

public class MyInterface { 

private WebView webView; 

//pass the reference to the webview in your constructor 
public JavascriptCallback(WebView webView) { 
    this.webView = webView; 
} 

//expose this method to the JS scope using annotation 
@JavascriptInterface 
void sumNumbers(final String num1, final String num2, final String JScallbackFn) { 
    this.javascriptCallback(JScallbackFn, num1 + num2); 
} 

//run the callback into the JS scope 
void javascriptCallback(final String callback, final String result) { 
    webView.post(new Runnable() { 
     @Override 
     public void run() { webView.load("javascript:"+callback+"("+result+")", null); 
     } 
    }); 
} 

2-注入的JavaScript界面​​的網頁視圖

webview.addJavascriptInterface(new MyInterface(this.getActivity(), webview), "MyInterface"); 

3-調用JS方法(從WebView中內)

MyInterface.sumNumbers(12, 34, showResult); 

function showResult(res) { 
    document.getElementById('myDiv').innerHTML(res); 
} 

有關網頁視圖如何適用於Android檢查的官方文檔http://developer.android.com/guide/webapps/webview.html

+0

更廣泛的解釋,我覺得it'sa有點複雜,調用JS方法獲取返回值,在ios中,webview支持調用js方法直接獲取返回值,非常感謝! – super5723 2015-02-13 02:37:08