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

时间:2015-07-13 08:01:31

标签: javascript android android-webview

我在我的活动中使用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);

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码 -

    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

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

将库添加到gradle中
相关问题