开发者

Android: is it possibile to alter the WebView class in order to have access to the html of the loaded page?

开发者 https://www.devze.com 2023-02-22 05:07 出处:网络
I need to use a WebView to load certain webpages and dynamically change the css before showing them to the user (which means I have to delete all <link> tags and append the one with my css). (Wh

I need to use a WebView to load certain webpages and dynamically change the css before showing them to the user (which means I have to delete all <link> tags and append the one with my css). (Why? Because I want to adapt the look of a particular site - which is not mine - for smartphones)

Now, I've seen that similar questions have been answered that the only way to modify the html before showing it to the user is by executing some javascript in the onPageFinished method; this could be a solution, but I'd like to consider other possibilities as well.

So, my questions are:

1) If I go deeper in the source of the WebView class, is it possible to find where the html is loaded from 开发者_开发知识库the site, so that I have direct access to the html and I can modify it as I want?

2) If yes, is WebView the class that handles the communication and retrieves the html? If else, which one is it?

3) Assuming that what I asked is possible, do you think that the application would perform better if the modification to the html where made this way instead of using javascript?


You can use HttpClient to perform an HTTP GET and retrieve the HTML response, something like this:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);

String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
    str.append(line);
}
in.close();
html = str.toString();

You can now have fun with your String html and place it in the Webview

    WebView webview=(WebView)findViewById(R.id.mywebview);
    webview.loadData(myModifiedHtml, "text/html", "UTF-8");


You can do it easily by enabling JavaScript on your webview and executing

document.getElementsByTagName('html')[0].innerHTML

Check this answer for detailed procedure.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号