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

标签 javascript android android-webview

我在 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 库 .

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

关于javascript - 使用 loadUrl() 在 android webview 中加载 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31378175/

相关文章:

javascript - 与 SVG 矩形内联的 Div

javascript - 如何在 JavaScript 上创建 div 并设置样式

java - 设置android.webkit.Web TextView类的文本颜色?

android - 如何在Android中的WebView中显示网站的一部分

android - Kitkat 应用程序将在 Lollipop 版本中运行吗

android - 需要帮助从 stock android 浏览器更改为 webview

javascript - $rootScope.$emit 不工作

javascript - Ios 设备, "required"字段和感谢消息

iphone - 在 iPhone、Android 和 Web 应用程序中重用代码

android设备监视器,发生错误,查看日志文件