title: Run JavaScript in Android webview
body: <p>I've been trying for several hours to run some <code>Javascript</code> in an android webview in which there is <code>html</code> parsed by <code>Jsoup</code>. And despite all my attempts to make it work, I'm still not able to do it.</p>
  
  <p>I've searched all over Google and tried all the answers I found, however none of them did the trick I tried using a method and here's what I ended up with:</p>
  
  <pre><code>Document doc = Jsoup.connect("http://example.com/").get();
  Elements web_body = doc.select("body").first().children();
  Elements web_head = doc.select("head").first().children();
  
  String javascript = "document.querySelector('h1').innerText='f';"; //Replaces 'Example Domain' with 'f': just an example js code.
  
  WebView webview = findViewById(R.id.webview_id);
  webview.getSettings().setJavaScriptEnabled(true);
  webview.getSettings().setDomStorageEnabled(true);
  
  String html_content = "&lt;html&gt;" + "&lt;head&gt;" + web_head.toString() + "&lt;/head&gt;" + "&lt;body&gt;" + web_body.toString() + "&lt;/body&gt;" + "&lt;/html&gt;";
  webview.loadDataWithBaseURL("", html_content, "text/html", "UTF-8", "");
  
  if (android.os.Build.VERSION.SDK_INT &gt;= android.os.Build.VERSION_CODES.KITKAT) {
      webview.evaluateJavascript(javascript, null);
  } else {
      webview.loadUrl("javascript:(function(){" + javascript + "})()");
  }
  </code></pre>
  
  <ul>
  <li>The code above shows the example page but javascript doesn't work at all: the app doesn't show any error messages nor crashes.</li>
  <li>I'm using a phone with Android O (8.0).</li>
  </ul>
  
  <p>I hope the above information will be useful. I'm still a beginner in Java and any help would be greatly appreciated!</p>