2016-11-10 35 views
2

真的沒有任何理想的,爲什麼這不起作用。基本上,我正在嘗試這樣做。Android的webview javascript界面​​不能正常工作

public void testJS() { 
     final WebView webView = (WebView) findViewById(web); 
//  webView.getSettings().setDomStorageEnabled(true); 
     webView.getSettings().setJavaScriptEnabled(true); 
     webView.addJavascriptInterface(new JSInterface(webView), "sample"); 
     webView.setWebChromeClient(new WebChromeClient() { 
      @Override 
      public boolean onJsAlert(WebView view, String url, String message, JsResult result) { 
     /* Do whatever you need here */ 
       Log.e("chrome", "asdf"); 
       return super.onJsAlert(view, url, message, result); 
      } 


     }); 
     webView.loadUrl("javascript:window.sample.doEchoTest();void(0);"); 
    } 

,這是JSInterface

public class JSInterface { 
     WebView mAppView; 

     public JSInterface(WebView appView) { 
      this.mAppView = appView; 
     } 

     public void doEchoTest() { 
      Log.e("sample", "test details"); 
      Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT); 
      toast.show(); 
     } 
    } 

的JavaScript代碼運行永遠。

基本功能,如警告作品:

webView.loadUrl("javascript:alert('sample')"); 

爲什麼webView.loadUrl("javascript:window.sample.doEchoTest();void(0);"); 不工作?

回答

1

只是瀏覽一個不同的答案,猜測這將是你沒有暴露它可以從JS訪問。你需要明確地爲每種方法這樣做:

@JavascriptInterface 
public void doEchoTest() { 
      Log.e("sample", "test details"); 
      Toast toast = Toast.makeText(mAppView.getContext(), "sample test details", Toast.LENGTH_SHORT); 
      toast.show(); 
     } 
+0

歡迎來到堆棧溢出!請隨時參加本網站的[tour](// stackoverflow.com/tour),如果您需要網站的其他幫助,請查看[this](// stackoverflow.com/help)。哦,如果您遇到過幫助頁面未涵蓋的問題,請隨時諮詢[meta](// meta.stackoverflow.com/)。 –