removing headers and footers in android webview

此生再无相见时 提交于 2021-01-28 08:52:57

问题


I am trying to load a responsive webpage in a webview component. But I would like to strip the header and footer of the webpage and load the webview with just the body of the webpage. How can this be achieved in an android webview.

<div class="header-container">
<header class="header clearfix" ng-include="'/modules/core/homepage/header-partial.html'"></header>
</div>

回答1:


I was able to remove the header and footer and load the webpage using loadDataWithBaseURL() method

Document document = Jsoup.connect(mUrl).get();
document.getElementsByClass("header-container").remove();
document.getElementsByClass("footer").remove();
WebSettings ws = mWebView.getSettings();
ws.setJavaScriptEnabled(true);
//mWebView.loadData(document.toString(),"text/html","utf-8");
mWebView.loadDataWithBaseURL(mUrl,document.toString(),"text/html","utf-8","");

As per the developer docs :

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

http://developer.android.com/reference/android/webkit/WebView.html#loadData(java.lang.String, java.lang.String, java.lang.String)




回答2:


If you want to edit html, i'd recommend using a html parser like jsoup. Them remove header and footer, and lastly load the data into a WebView

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();
}


来源:https://stackoverflow.com/questions/29925677/removing-headers-and-footers-in-android-webview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!