2016-12-27 87 views
0

我有一個代碼在這裏,我想從android的webview中檢索一個元素,我似乎無法弄清楚什麼是錯的。這可能是一些愚蠢的錯誤,但我不明白爲什麼和錯在哪裏。謝謝。JavaScript不工作在WebView - Android

private void retrieveContentWebView(String address){ 

    Log.d("Web Download"," Inside "); 
    Log.d("Web Download ","address : " + address); 

    WebView webView; 

    webView = new WebView(context); 
    webView.loadUrl(address); 

    webView.getSettings().setJavaScriptEnabled(true); 
    webView.addJavascriptInterface(this, "myjava"); 


    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
     webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); 

    webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); 
    webView.getSettings().setDomStorageEnabled(true); 

    webView.setWebViewClient(new WebViewClient() { 

     @Override 
     public void onPageStarted(WebView view, String url, Bitmap favicon) { 
      super.onPageStarted(view, url, favicon); 
      Log.d("Web Download"," Inside Page Started"); 

     } 

     @Override 
     public void onPageFinished(WebView view, String url) { 
      super.onPageFinished(view, url); 

      Log.d("Web Download"," Inside Page Finished"); 

       view.loadUrl("javascript: {" + 
         "var titleTexts = document.getElementsByTagName('title')[0]" + 
         "myjava.onData(titleTexts.text);}"); 

     } 
    }); 

} 

//This method will be registered as a JavaScript interface 
@JavascriptInterface 
@SuppressWarnings("unused") 
public void onData(final String value){ 

    Log.d("Web Download"," Inside Handler"); 

    final String getValue = value; 

    final Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      // Do something after 5s = 5000ms 
      Log.d("Web Download HTML :",getValue); 
     } 
    }, 5000); 


} 
+0

getElementsByTagName('title')[0]'後面應該有分號嗎?否則,將直接進入以'myjava'開頭的下一行。 – Bobulous

回答

1

嘗試添加以下內容到WebView

webView.setWebChromeClient(new MyCustomChromeClient(this)); 

爲自己創建的MyCustomChromeClient。