Android WebView Disable Iframe Loading - java

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

Related

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

Loading html data from page source into webview

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.

How to catch an iframe redirecting?

I have a WebView with an iframe inside. The contents of the iframe do a redirect to another URL that doesn't allow embedding in an iframe. Not a problem, actually, I just want to start the external browser activity in this case instead. The problem is that I can't find a way to intercept the redirection. None of shouldOverrideUrlLoading(), onPageStarted() or onLoadResource() get called for the redirect, hence I get no chance to start the activity.
In the html change the iframe tag to call some javascript function when a redirect happens
example: iFrame src change event detection?
For anyone else with this problem, we found an even more simple solution to this than calling a javascript function. Simply add "target= _top" to the iframe redirect (see http://www.w3schools.com/tags/att_a_target.asp). Then shouldOverrideUrlLoading() will be called in the Android code.

call response.redirect from inner div of a page to load a new page onto the browser

I'm loading a some page content to an inner div called 'center_column' in my index.jsp using ajax load method.
$('#center_column').load('abc.jsp', function() { });
but while it is loading I want to check for the session time out and redirect the request to login page. This session time out code is in within the 'abc.jsp'
I used
response.sendRedirect("login.html");
method for it. But this will reload the login.html with in the #center_column div.
But I want to load login.html onto the browser instead of the existing page ( index.jsp) on the browser. And also I want to fix this without using javascript.
Can anyone guide me to solve this issue please
Thanks
You have to use javascript, but it's minimal. Try handling your session check on the server like this:
if (request.getSession(false) == null) {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
Then in your callback function on the client side,
$('#center_column').load('abc.jsp', function(responseText, textStatus, xhr) {
if (xhr.status == 403)
window.location = '/login.html';
});

Java Android WebView Displaying a string

i have an application that fetch html from a websites, exactly in a webpage permitted only tu logged in user, so i have setted the login cookie and i get back the html webpage to a string, i tryied to easily take this string off from emulator, but i can't do copy-paste trought emulator-pc, does someone know how can i load a webview to reder my string and make me seeing if i am logged in and all work or not?
If it's possible i'd like to directly render the string, without saving it to an html file and opening it... is this possible?
Thanks, matteo.
Setting webview content form String:
public static void loadHtmlToWebView(WebView view, String html) {
view.loadData(Base64.encodeToString(html.getBytes(), Base64.DEFAULT) , "text/html", "base64");
}

Categories