Loading html data from page source into webview - java

I'm trying to load a page in my webview by copying the html source (right click page, select 'View page source') and pasting it into my HTML file that I have in my android's 'assets' folder.
The problem I encounter is that when I use webview.loadUrl(myUrl); it loads the page but it's mostly black and white, I dont see any colors.. usually only the links show (the links are clickable but don't work, they just give me a Webpage not available error) and thats about it.
How would I fix this behavior?
my code looks like this
#SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.myWebview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
view.loadUrl(url);
return false;
}
});
String myUrl = "file:///android_asset/Assets.html";
webView.loadUrl(myUrl);
}
the Assets.html file contains all the HTML code obviously.

I found the problem.
It was the encoding.
Unfortunately I am not sure what encoding to use but this is how I solved it.
When I copied the source from a different web page, and tried to run my app, an error showed up, it said that certain characters contained in the HTML source needed a different encoding to run, as soon as I selected "Change encoding" within the message that popped up, and ran the app, the website loaded fine.

Related

PDF not loading When I click on a link in a website server in my WEBVIEW app

I'm a newbie to android and I have made a webview android app. It belongs to a website . The website have many many pdf files in it, Which are in links . When I search a desirable file and found the file in my webview app and click on the link to open the pdf file it does not load pdf file . The link is embedded in a text like "view file". When I click on view file it does not load pdf file .
Thanks in advance if you have a solution to my question.
You can load pdf in webview like below
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.endsWith(".pdf")) {
String googleDocs = "https://docs.google.com/viewer?url=";
view.loadUrl(googleDocs + url);
} else {
webView.loadUrl(url);
}
return true;
}
}

How to retrieve and modify HTML content from WebView with Http Post

I'm developing an android app that shows some part of a HTML page. For the first step, I use this code provided in question How to retrieve HTML content from WebView.
Full html picture
That part i want to show
/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
#SuppressWarnings("unused")
public void processHTML(String html)
{
// process the html as needed by the app
}
}
final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);
/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
/* This call inject JavaScript into the page which just finished loading. */
browser.loadUrl("javascript:window.HTMLOUT.processHTML('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');");
}
});
/* load a web page */
browser.loadUrl("http://example.com/gethtml.html");
but when a user click on a button in second picture a HTTP post method will be called and this will be the result HTML
my question is how retrieve and modify the Post Result Html before showing to user? and show something like this
A simple solution could be to inject custom css code inside your webview, changing the style of the HTML element you want to display "alone".
You should inject a css like this:
#central-box {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
// depends on the structure of the page
}
See also in this answer for an example of how to do it.
There are at least three ways to do this that I can think of and you're really close to all of them:
You already have a rough idea of the quick and dirty method, from #lifeisfoo, although to handle both GET and POST pre-API 21 you would need to use onPageCommitVisible(WebView view, String url). As onPageFinished(WebView view, String url) and shouldOverrideUrlLoading (WebView view, String url) only trigger on GET requests.
Here's why, straight from the SDK...
..."onPageCommitVisible callback can be used to determine the point at which it is safe to make a recycled WebView visible, ensuring that no stale content is shown. It is called at the earliest point at which it can be guaranteed that onDraw(Canvas) will no longer draw any content from previous navigations. The next draw will display either the background color of the WebView, or some of the contents of the newly loaded page." it's called on all content updates POST or GET.
Slightly better, you can create a local proxy web page with the javascript interface and other fun bits already in place and stored as a resource, if the content you want is loaded into full-window iframe you can get really good control, you can interact with your proxy using onPageFinished since it's in an iframe you can interact with the target page using onLoadResource, handle interception using the old shouldInterceptRequest which returns a WebResourceResponse and deal with POST driven updates using onFormResubmission.
Finally, If API support earlier than 21 isn't a big issue the best method would be to use the new shouldInterceptRequest which takes the new WebResourceRequest object that allows you to specify different handling for different request types.
Here's the API Links for the new WebResourceRequest object and the new shouldInterceptRequest method on the WebViewClient...
http://developer.android.com/reference/android/webkit/WebResourceRequest.html
http://developer.android.com/reference/android/webkit/WebViewClient.html#shouldInterceptRequest(android.webkit.WebView, android.webkit.WebResourceRequest)
hope that helps :)

Android edit stored .html page

I have a locally stored HTML file in my assets folder that I am accessing through this:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
WebView webView = new WebView(this);
setContentView(webView);
webView.loadUrl("file:///android_asset/test.html");
}
I was wondering if there is any way I would be able to edit the source of the HTML file loaded, as I may need to manipulate certain elements.
ex. I have a <h3>Johny</h3> in the test.html, How can I change it by using an edittext?
I know how to use and show and get results form an edittext, but then, how to replace what is from the edittext to the <h3> tags in replacement to Johny?

Android WebView Disable Iframe Loading

In my app I have an WebView which displays some webpages.
Some webpages contain iframes. and some iframes load alertboxes, confirmboxes, prompts and popups.
I want to block loading that iframe but not loading it? or atleast disable these popups (without disabling javascript)
I tried to block these pages by filtering them by following method
in the on page started method
use the if condition to match the url with the url which gives popups
if matched restart the webview
however i found that the url is always of the main site and not the site the iframe loads so if statement is never true
how do I block the iframe or popups?
any help would be appreciated
thankyou
You need to implement WebViewClient and override shouldOverrideUrlLoading.
Check if it's an iframe with if (!request.isForMainFrame()).
Then you can manually load the content of the url and sanitize it.
#TargetApi(24)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (!request.isForMainFrame()) {
if (shouldBlock(request.getUrl()))
return true;
}
return super.shouldOverrideUrlLoading(view, request);
}

WebView not Loading Data?

I'm trying to load the parsed html data from an rss feed using a
WebView, but the webview claims that the page:
"data:text/html;utf-8,[The html I'm trying to display]"
is not available.
I find it strange that it seems to be putting the html data into the
url, when I just want it to display it.
Here's my code right now for the webview:
Bundle data = getIntent().getExtras();
WebView webview = new WebView(this);
setContentView(webview);
webview.loadData(data.getString("DEFAULTTEXT"), "text/html", "utf-8");
Where the HTML has been passed in a string in the Bundle with the
identifier: DEFAULTTEXT. I've tested the class and the HTML is passed
fine, it just isn't displayed correctly.
It works fine on some of the webpages I've tried, but not others. I'll try to post the code of one that works and one that doesn't.
Huuu.... so I turned my computer on this morning and it worked perfectly. I still don't know what the problem was. :/
Edit: Never mind. It works on some, but not all of the pages I try to display.
Edit2: swapping it out for loadDataWithBaseURL worked like a charm.
As stated, when you have characters like '%', '\', '#' in your HTML, it needs to be escaped which loadData doesn't seem to do automatically.
loadDataWithBaseURL instead of loadData does escape and seems to fix this. Just use null for baseUrl and historyUrl. So the example code in the question is changed to:
Bundle data = getIntent().getExtras();
WebView webview = new WebView(this);
setContentView(webview);
webview.loadDataWithBaseURL(null,data.getString("DEFAULTTEXT"), "text/html", "utf-8",null);
I believe this sporadic behavior of loadData* is because of what is the content of the page you are trying to load. If it is plain simple html it has no problem. But if it has components like css or other features requiring external info, it will bail out.
My experience!
Are you sure you have the correct permissions defined in the manifest.xml?

Categories