WebView is not using Cookies for loading images - android

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

Related

loading only a specific element properly in webview

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.

WebView shows source html with loadDataWithBaseURL, not rendered view

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.

webview not loaded images

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.

Display a part of the webpage on the webview android

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

How to pass parameter into HTML file from android

I can show up HTML file content in android webview well.Now how could i pass parameter into HTML file.For ex.my HTML content has an video player
i need to pass dynamic values(URL) into HTML file for playing dynamic video.My HTML file is located on asset folder.How could i do this?
Thanks.
I came upon this problem today, however I needed this to work with UTF-8 encoding, so this was my approach, hopefully it will help someone and clarify some of the previous answers to this question.
HTML:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<h1>%ERR_TITLE%</h1>
<h2>%ERR_DESC%</h2>
</body>
</html>
Java:
String content = IOUtils.toString(getAssets().open("error.html"))
.replaceAll("%ERR_TITLE%", getString(R.string.error_title))
.replaceAll("%ERR_DESC%", getString(R.string.error_desc))
mWebView.loadDataWithBaseURL("file:///android_asset/error.html", content, "text/html", "UTF-8", null);
As for IOUtils:
http://commons.apache.org/proper/commons-io/download_io.cgi
Instead of passing directly the video URL (following you example), i would have used tokens in the Html file. For example:
<embed src="$VIDEO_URL$" autostart="false" />
where the $VIDEO_URL$ will be the token wich will be replaced during the runtime with a real video URL.
Also, since you cannot change the contents of your asset folder during runtime you should load the html file contents into a String variable and use the replace method to replace the token with a real URL and, finally, pass that string to your webview. Something like this:
//The html variable has the html contents of the file stored in the assets folder
//and real_video_url string variable has the correct video url
html = html.replace("$VIDEO_URL$", real_video_url);
webview.loadData(html, "text/html", "utf-8");
If i would like to have something dynamic in my HTML i would have an html with dynamic parts written like this:
<B>%NAME%</B>
Then i would load my HTML:
String template = Utils.inputStreamToString(assets.open("html/template.html"));
then
Then i would replace all dynamics parts with what i want like this:
String data = template.replaceAll("%NAME%", "Alice McGee");
then i would pass it to my webView!
WebView webView = new WebView(this);
webView.loadDataWithBaseURL("file:///android_asset/html/", data, "text/html", "utf-8", null);
I managed to pass variables in a different way.
My problem was that everytime I switched to another app, when coming to the webapp, the webview kept reloading. I guess that's because of the following line in my onCreate() method: myWebView.loadUrl(url); I had the idea to pass these state variables in the url, but as you know it is not possible yet.
What I did was to save the state of some variables using onSaveInstanceState(Bundle outState) {...} and restore them with onRestoreInstanceState(Bundle savedInstanceState){...}.
In onCreate method after setting up myWebView I did the following:
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String urlString)
{
Log.i("onPageFinished", "loadVariables("+newURL+")");
if(newURL!="")
myWebView.loadUrl("javascript:loadVariables("+"\""+newURL+"\")");
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
jsInterface = new JSInterface(this,myWebView);
myWebView.addJavascriptInterface(jsInterface, "Android");
if (savedInstanceState != null)
{
// retrieve saved variables and build a new URL
newURL = "www.yoururl.com";
newURL +="?var1=" + savedInstanceState.getInt("key1");
newURL +="?var2=" + savedInstanceState.getInt("key2");
Log.i("myWebApp","NEW URL = " + newURL);
}
myWebView.loadUrl("www.yoururl.com");
So, what it happens is that first I load the page with the default URL (www.yoururl.com) and onPageFinished I call a new javascript method where I pass the variables.
In javascript loadVariables function looks like this:
function loadVariables(urlString){
// if it is not the default URL
if(urlString!="www.yoururl.com")
{
console.log("loadVariables: " + urlString);
// parse the URL using a javascript url parser (here I use purl.js)
var source = $.url(urlString).attr('source');
var query = $.url(urlString).attr('query');
console.log("URL SOURCE = "+source + " URL QUERY = "+query);
//do something with the variables
}
}
here assets means what?
String template = Utils.inputStreamToString(assets.open("html/template.html"));

Categories

Resources