使用 loadUrl() 在 android webview 中加载 JavaScript

Load JavaScript in android webview using loadUrl()

我在 activity 中使用 webview 来显示网页,并使用 javascript 来隐藏页眉。

我在 chrome 控制台中尝试了以下脚本,它工作正常:document.getElementsByClassName('Header')[0].style.display = 'none';

当我在 android webview 中使用相同的脚本时,页面被清除并显示 none 这是脚本的输出。 (也在 Chrome 控制台上收到)。

String s = (new StringBuilder())
  .append(" javascript:  document.getElementsByClassName('Header')[0].style.display = 'none';")
  .toString();
webView.loadUrl(s);

您可以使用以下代码 -

    try {

        // Load the html into jsoup
        Document doc = Jsoup.connect("http://your-site.com/").get();

        // find and remove header
        Element header = doc.getElementById("your-header");
        header.remove();

        // find and remove footer
        Element footer = doc.getElementById("your-footer");
        footer.remove();

        // Load data into a WebView
        WebView wv = (WebView) findViewById(R.id.webView);
        WebSettings ws = wv.getSettings();
        ws.setJavaScriptEnabled(true);
        wv.loadData(doc.toString(), "text/html", "utf-8");

    } catch (IOException e) {
        e.printStackTrace();
    }

您将在 this link 找到最新的 Jsoup Library

可以通过添加以下依赖项将库添加到 gradle compile 'org.jsoup:jsoup:1.8.2'