2014-02-15 26 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"); 
    } 
相关问题