it's needs to insert loaded from url html data into webview.
my code
private String getHtmlFromURLJsoup(String url) throws IOException{
Document doc = Jsoup.connect(url)
.userAgent("Mozilla")
.cookie("auth", "token")
.timeout(10000)
.get();
return doc.html();
}
mWebView.loadUrl("javascript:(function () { " +
"setMainContent('" + getHtmlFromURLJsoup(s).replaceAll("\n", "").replaceAll("'", "") + "');" +
"})()");
Content loaded fine, but images not displayed. How can I load html from url with data (images, styles, scripts...)?
Try this method from WebView:
loadDataWithBaseURL(null, htmlBody, "text/html", "UTF-8", null);
htmlBody - your html downloaded data.
Also try to change String to CharSequence in your method:
private CharSequence getHtmlFromURLJsoup(String url) throws IOException{
Are you asking how to implement your own webbrowser?
The html will have links to those other things (images, styles, scripts...) - you need to locate the links in the html and go and fetch them separately - this is what a web browser does.
Related
i am trying to load only a specific element in my webview webpage ('contentbody').
but i dont know how to modify my code to load that only. i can block elements in my webview by using this simple javascript.
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
// Removes element which id = 'mastHead'
view.loadUrl("javascript:(function() { "
+ "(elem = document.getElementById('smsform')).parentNode.removeChild(elem); "
+ "})()");
}
An option might be to use Jsoup, to load the HTML page from the website, extract the desired portion of the HTML, and then load just that into your WebView. A small example of how it could be done:
Document doc = Jsoup.connect("http://example.com/").get();
myWebView.loadDataWithBaseURL("http://example.com/", doc.select(".contentbody").first().outerHtml(), "text/html", "UTF-8", null);
With this, you use Jsoup to extract the first item with contentbody class from the HTML, and then directly load it into your WebView.
I wanna save all web page including .css .js on android by programmatically.
So far I tried html get method and jsoup , webview content but all of them I could not save all page with css and js. These methods just save html parts of WEB Page. When I save the all page ,I want to open it offline.
Thanks in advance
You have to take the html, parse it and get the urls of the resources and then make requests for those urls too.
public class Stack {
private static final String USER_AGENT = "";
private static final String INITIAL_URL = "";
public static void main(String args[]) throws Exception {
Document doc = Jsoup
.connect(INITIAL_URL)
.userAgent(USER_AGENT)
.get();
Elements scripts = doc.getElementsByTag("script");
Elements css = doc.getElementsByTag("link");
for(Element s : scripts) {
String url = s.absUrl("src");
if(!url.isEmpty()) {
System.out.println(url);
Document docScript = Jsoup
.connect(url)
.userAgent(USER_AGENT)
.ignoreContentType(true)
.get();
System.out.println(docScript);
System.out.println("--------------------------------------------");
}
}
for(Element c : css) {
String url = c.absUrl("href");
String rel = c.attr("rel") == null ? "" : c.attr("rel");
if(!url.isEmpty() && rel.equals("stylesheet")) {
System.out.println(url);
Document docScript = Jsoup
.connect(url)
.userAgent(USER_AGENT)
.ignoreContentType(true)
.get();
System.out.println(docScript);
System.out.println("--------------------------------------------");
}
}
}
}
I have similar problem...
Using this code we can get images,.css,.js. However some html contents are still missing.
For instance when we save a web page via chrome,there are 2 options.
Complete html
html only
Out of .css,.js,.php..."Complete html" consists of more elements than "only html". The requirement is to download the html as complete like chrome does in the first option.
I'm developing an application witch uses WebView to render custom html.
But when I call
loadDAtaWithBaseURL(URL, "<html><h1>TEST</h1></html>", "text/html; charset=utf-8;", "utf-8", null);
it shows html itself (not rendered one) on Genymotion emulator.
On my HTC-one, it works fine with rendered html.
Each result is showed as attached.
Does anyone have a same problem or solution?
Thanks.
Don't enter mimeType below KitKat.
fun getMimeType(): String? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
"text/html; charset=utf-8"
} else {
null
}
}
loadDAtaWithBaseURL(URL, "<html><h1>TEST</h1></html>", getMimeType(), "utf-8", null);
Java:
if(Build.VERSION.SDK_INT < 21)
webView.loadDataWithBaseURL("about:blank","<html><h1>TEST</h1></html>","text/html", "UTF-8",null);
else
webView.loadDataWithBaseURL("about:blank","<html><h1>TEST</h1></html>","text/html; charset=utf-8", "UTF-8",null);
Regarding the info you have given, i can not have a clear debug for the issue, but this is how it should be done, just to check if you missed something
First, add this line to your activity in the manifest file
Load your data using
public void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl);
And this is done this way
loadDataWithBaseURL(Url, data, "text/html", "UTF-8", historyUrl)
Note that
If the base URL uses the data scheme, this method is equivalent to calling loadData() and the historyUrl is ignored, and the data will be treated as part of a data: URL. If the base URL uses any other scheme, then the data will be loaded into the WebView as a plain string (i.e. not part of a data URL) and any URL-encoded entities in the string will not be decoded.
I have troubles when I want my WebView to load images that requires Cookies.
I have set my cookies on the 'CookieManager'
final android.webkit.CookieManager instance = android.webkit.CookieManager.getInstance();
instance.setAcceptCookie(true);
instance.setCookie(".example.fr", mCookies, new ValueCallback<Boolean>() {
#Override
public void onReceiveValue(final Boolean value) {
loadWebView();
}
});
The WebView is then loaded with a custom HTML string because the app is generating the proper HTML.
private void loadWebView() {
// this string is an example of a generated HTML
String htmlContent =
"<!DOCTYPE html>" +
"<html><head>" +
"<link rel=\"stylesheet\" href=\"css/style.css\" type=\"text/css\" media=\"screen, projection\"/></head>" +
"<body><img src=\"www.example.fr/img.jpg\"/></body></html>";
mWebView.loadDataWithBaseUrl("file:///android_asset/", htmlContent, "text/html", "UTF-8", null);
}
I tried to proxy the network calls with Charles Proxy and I noticed that the request to www.example.fr/img.jpg had no cookie set in the headers. But, when I inspect the WebView using Chrome debbuging, I can see that the Cookies are properly under the Resources tab.
It seems that they are not used for the image downloading.
Any hints or advices to make the WebView using Cookies for resource downloading ?
Thank you.
I've faced with same problem, it is related with following changes:
https://developer.android.com/about/versions/android-5.0-changes.html#BehaviorWebView
to fix it you need set:
CookieManager.getInstance().setAcceptThirdPartyCookies(mWebView,true);
I want to make an app which loads the content from the webpage into webview. I want to show only a particular thing in the entire webview, not the whole content of the webpage.
Here is an example. If I use: http://us.m.yahoo.com/w/search%3B_ylt=A2KL8xs0vUBQMg0AwAkp89w4?submit=oneSearch&.intl=us&.lang=en&.tsrc=yahoo&.sep=fp&p=digital+cameras&x=0&y=0 as the URL for the webview, it loads all the contents of the page on the webview. But I want to remove the banner of the page and show it on the webview of my application.
I have tried using adblocker using CSS tags, but that is not helping me. Please give me some idea for overcoming this problem.
Thanks.
Thank You for the answer Zyber. I have solved it using injection of JavaScript in the code for WebView in android.
final WebView webview = (WebView)findViewById(R.id.browser);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
webview.loadUrl("javascript:(function() { " +
"document.getElementsByTagName('header')[0].style.display="none"; " +
"})()");
}
});
webview.loadUrl("http://code.google.com/android");
This solved my purpose and it is easy to use to.
I got the solution to add this:
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
view.loadUrl("javascript:(function() { " +
"var head = document.getElementsByClassName('header')[0].style.display='none'; " +
"var head = document.getElementsByClassName('blog-sidebar')[0].style.display='none'; " +
"var head = document.getElementsByClassName('footer-container')[0].style.display='none'; " +
"})()");
}
});
view.loadUrl("your url");
Adding (var head =) looks like to hide my class in webview.
I hope this will be helpful for someone.
check Jsoup it provides an library which gives an easy way of extracting Html elements from a webpage
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url.toURI());
HttpResponse resp = client.execute(get);
String content = EntityUtils.toString(resp.getEntity());
Document doc = Jsoup.parse(content);
Elements ele = doc.select("div.classname");
This example executes an Http GET and then extracts an Div element with the class "classname" which you can then load in your webview