2014-02-15 62 views
0

我在JSTest類和JSInterface下面使用獲得了javascript結果 但是「processJsReturnValue」函數沒有被調用。 我的錯誤是什麼?如何在android上運行javascript並獲取結果

public class JSTest { 
    private String jsReturnValue =null; 
    private WebView webView; 
    public Context mContext; 

    private static class JSInterface { 
    private JSTest myContext; 

    public JSInterface(JSTest context) { 
     this.myContext = context; 
    } 

    @JavascriptInterface 
    public void processReturnValue(String value) { 
     myContext.processJsReturnValue(value); 
    } 
    } 

    public JSTest(Context context) { 
    super(); 
    mContext = context; 
    webView = new WebView(context); 
    webView.getSettings().setJavaScriptEnabled(true); 
    webView.addJavascriptInterface(new JSInterface(this), "androidInterface"); 
    String jsString = "(function(){"+ 
      "window.androidInterface.processReturnValue('abc');"+ 
     "})();"; 
    webView.loadUrl("javascript:"+jsString); 
    } 

    public void processJsReturnValue(String value) { 
    Log.e("got it", value); 
    jsReturnValue = value; 
    } 
} 
+0

如果你的'jsString'改變發生什麼:'字符串jsString =「androidInterface.processReturnValue( 'ABC') ;「'? – Jite

+0

它是一樣的.. –

+0

你是否100%肯定'processJsReturnValue'函數沒有被調用?你在Javascript中遇到任何錯誤嗎?或者在android端? – Jite

回答

0

我解決它@吉特的幫助

解決方案:

public JSTest(Context context) { 
    super(); 
    mContext = context; 
    webView = new WebView(context); 
    // chromeClient = new CustomWebChromeClient(); 
    //webView.setWebChromeClient(chromeClient); 
    webView.getSettings().setJavaScriptEnabled(true); 
    jsinterface = new JSInterface(this); 
    webView.addJavascriptInterface(jsinterface, "androidInterface"); 
    webView.setWebViewClient(new WebViewClient() { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) { 
      Log.e("", "do loading"); 
      return true; 
     } 

     @Override 
     public void onPageFinished(WebView view, String url) { 
      super.onPageFinished(view, url); 
      Log.e("", "do loading finished"); 
      String jsString = "window.androidInterface.processReturnValue('abc');"; 
      webView.loadUrl("javascript:"+jsString); 


     } 
    }); 
    webView.loadData("<html></html>", "text/html", "utf8"); 
    } 
相關問題