Android - Image Loading from WebPage in WebView - android

I am trying to load a wiki web page into a native Android WebView with WebView.loadUrl(String url). It works and displays all of the web content, except for the images. However, I have not found a reason for this. Does anyone know why image resources would not load automatically? Is there a method I need to overwrite or a parameter that needs to be set? I can't find anything in the documentation - it looks like the default settings should allow for automatic image loading. Any information would be appreciated. Thanks!
mWebView = (WebView)findViewById(R.id.webView);
setWebViewClient(mWebView);
setWebSettings(mWebView);
mWebView.loadUrl("http://my_wiki_url_goes_here/");
private void setWebViewClient(WebView mWebView) {
WebViewClient client = new WikiWebViewClient();
mWebView.setWebViewClient(client);
}
private void setWebSettings(WebView mWebView) {
WebSettings settings = mWebView.getSettings();
settings.setJavaScriptEnabled(true);
}
public class WikiWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
}
Printing the url onLoadResource(), I see that the image urls generally start with "data:image/png;base64,". I don't think that should makes a difference or not - it works in the web browser.

Huh, looks like simply enabling DOM storage did the trick.
settings.setDomStorageEnabled(true);
If I don't receive a better explanation or solution, I will accept this answer once I am able to

Related

The mystery of the disappearing URL

So I've been trying to get one of my activity to display a published google sheet webpage... and I managed to get it working on my emulator (nexus 5, API 22) but when I run the app on my phone (Samsung galaxy S7) it printed out a toast message "failed to find document. it is possible the document has been deleted"
I've tried testing with and it works in both the emulator and the phone so I think the code serves it's purpose. I really don't understand...
here is a copy of my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_schedule);
WebView webView = new WebView(this);
webView.loadUrl("https://docs.google.com/spreadsheets/d/e/2PACX-1vSnBA-tNsQsUKOUCs8PkdADgMP2n4TFyl8JtKFkxUanIoXbcC9xuzY89Xw9oIRCL0ane3MKpZYRFrP1/pubhtml?gid=0&single=true");
WebSettings settings = webView.getSettings();
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
}
I assume Google is redirecting your url to another url. So can you try the below code for handling redirect urls in WebView.
mWebView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});

WebViewClient not calling shouldOverrideUrlLoading

The problem is rather simple.
In the application we want to keep track of the current url being displayed. For that we use shouldOverrideUrlLoading callback from the WebViewClient by saving the url into a class field for every update. Here is the relevant code:
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setDomStorageEnabled(true);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mCurrentUrl = url;
// If we don't return false then any redirect (like redirecting to the mobile
// version of the page) or any link click will open the web browser (like an
// implicit intent).
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
...
}
});
mWebView.loadUrl(mInitialUrl);
However, there is at least one scenario, where the callback never gets triggered and the mCurrentUrl field doesnt get updated.
The url: https://m.pandora.net/es-es/products/bracelets/556000
Last updated url (shouldOverrideUrlLoading never gets called when clicking the product): https://m.pandora.net/es-es/products/bracelets
I have tried with callbacks like onPageStarted(), but the url also gets filtered and there doesn't seem to be an accessible one upstream since its protected code.
Reading android documentation about WebView I found this:
https://developer.android.com/guide/webapps/migrating.html#URLs
The new WebView applies additional restrictions when requesting resources and resolving links that use a custom URL scheme. For example, if you implement callbacks such as shouldOverrideUrlLoading() or shouldInterceptRequest(), then WebView invokes them only for valid URLs.
But still doesnt make sense since the above url is generic and should meet the standard.
Any alternative or solution to this?
When you click a product on that web page, it loads the new content in with JavaScript and updates the visible URL in the address bar using the HTML5 History APIs.
From the above MDN article:
This will cause the URL bar to display http://mozilla.org/bar.html, but won't cause the browser to load bar.html or even check that bar.html exists.
These are sometimes called single-page applications. Since the actual loaded page doesn’t change, the WebView callback for page loads isn’t called.
In case you know precisely what kind of HTTP request you want to intercept, you could use the shouldInterceptRequest callback that gets called for each request. It’s likely that the web application loads some data from an API, for example when a product is shown, which you could then detect.
If detecting this isn’t possible, but you’re in control of the web application, you could use the Android JavaScript interface to invoke methods within the Android application directly from the web page.
If you’re not in control of the loaded page, you could still try to inject a local JavaScript file into the web page and observe when the history APIs are used, then call methods in your Android application over the JS interface. I tried observing these events in Chrome with the method described in the previous link and it seems to work fine.
Maybe this helps someone, although the signature in the question is correct, but Android Studio suggests the following method signature:
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
which then never called. It took me a while to notice that the right signature is:
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Sorry if this not 100% fit the question, but I believe this may help someone in the same situation. It's not always easy to notice that the second parameter is different.
Please omit mWebView.getSettings().setDomStorageEnabled(true);
Then again try, if a new url found then will invoke shouldOverrideUrl()
I had the same problem like you, and I've finished with extending of WebViewChromeClient with listening for callback to
public void onReceivedTitle(WebView view, String title)
mWebView.setWebChromeClient(mSWWebChromeClient);
private WebChromeClient mSWWebChromeClient = new WebChromeClient() {
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (!view.getUrl().equals(mCurrentUrl)) {
mCurrentUrl = view.getUrl();
//make something
}
}
};
For me the problem was below line -
mWebView.getSettings().setSupportMultipleWindows(true);
After removing it shouldOverrideUrlLoading was being called.
after stumbling on this problem and searching for solutions, I've found the one that worked perfectly for me
https://stackoverflow.com/a/56395424/10506087
override fun doUpdateVisitedHistory(view: WebView?, url: String?, isReload: Boolean) {
// your code here
super.doUpdateVisitedHistory(view, url, isReload)
}
Another approach you can try: Catch the url by javascript side. Initialize your webView with this:
webView.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
After page is completely loaded (You can use an algorithm to check this like this https://stackoverflow.com/a/6199854/4198633), then:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.evaluateJavascript("(function() {return window.location.href;})", new ValueCallback<String>() {
#Override
public void onReceiveValue(String url) {
//do your scheme with variable "url"
}
});
} else {
webView.loadUrl("javascript:Android.getURL(window.location.href);");
}
And declare your WebAppInterface:
public class WebAppInterface {
Activity mContext;
public WebAppInterface(Activity c) {
mContext = c;
}
#JavascriptInterface
public void getURL(final String url) {
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//do your scheme with variable "url" in UIThread side. Over here you can call any method inside your activity/fragment
}
});
}
}
You can do something like that to get url, or anything else inside the page.
Add
webView.getSetting().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
then shouldOverrideUrl will be triggered.
onProgressChanged is always triggered when reloading, loading new page with userclick or XmlHttpRequest.
Compare the URL of previous load and the current load, you'll know it's reloading or loading a new page. This works perfect in my single page Web App.
First declare a global variable to store last URL.
String strLastUrl = null;
Then override onProgressChanged(WebView view, int progress)
mWebView.setWebChromeClient(new MyWebChromeClient(){
#Override
public void onProgressChanged(WebView view, int progress) {
if (progress == 100) {
//A fully loaded url will come here
String StrNewUrl = view.getUrl();
if(TextUtils.equals(StrNewUrl,strLastUrl)){
//same page was reloaded, not doing anything
}else{
//a new page was loaded,write this new url to variable
strLastUrl = StrNewUrl;
//do your work here
Log.d("TAG", "A new page or xhr loaded, the new url is : " + strLastUrl);
}
}
super.onProgressChanged(view, progress);
}
});
I've also tried above solutions, but most of them have issue in my case:
doUpdateVisitedHistory sometimes can not return correct url after "#" made by XmlHttpRequest.
My case is a single page web App. The web App uses javascript with
xhr to display new page when user click an item. For example, user is
currently at http://example.com/myapp/index.php , after clicking, the
browser url becomes
http://example.com/myapp/index.php#/myapp/query.php?info=1, but in
this case, doUpdateVisitedHistory returns
http://example.com/myapp//myapp/
onReceivedTitle doesn't work in my case because the response retrieved by XMLHttpRequest does not have <title></title> tag.
The JavascriptInterface method also works, but I'm afraid it will cause
security related issues with javascript.
public class AndroidMobileAppSampleActivity extends Activity {
/** Called when the activity is first created. */
String mCurrentUrl="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView mWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyCustomWebViewClient());
mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mWebView.loadUrl("https://m.pandora.net/es-es/products/bracelets/556000");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
mCurrentUrl = url;
Log.i("mCurrentUrl",""+mCurrentUrl);
view.loadUrl(url);
return true;
}
}
}
try this one...

Denied starting an intent without a user gesture Webview Android

Trying to redirect local html page in android webview using Javascript redirect, gets denied starting an intent in Logcat:
Testing on android 5.1.1
document.location = "index.html";
Denied starting an intent without a user gesture, URI:
file:///android_asset/index.html
I read the documentation in 1,000 attempts Android.developer and this was my solution
I do not know if you understand, I speak Spanish
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
This worked for me:
webView.setWebViewClient(new WebViewClient());
There are few issues here.
From newest androids, the WebView and Chrome Client is separated application which can be automatically updated without user intention.
From Chrome x >= 25 version, they changed how loading url is working in android application which is using webview component. https://developer.chrome.com/multidevice/android/intents Looks like they are blocking changing url without user gesture and launched from JavaScript timers
Solution here is to force user to activate URL change, for example on button click.
Also, you can override method mentioned above "shouldOverrideUrlLoading" in WebView client.
As alternate, i figured out was to add addJavascriptInterface each button click event fire action to JavascriptInterface
webView.addJavascriptInterface(new java2JSAgent(), "java2JSAgentVar"); //webView webview object
public class java2JSAgent
{
#JavascriptInterface
public String getContacts()
{
String jsonResponse = "{result:'redirected'}";
runOnUiThread(new Runnable() {
#Override
public void run() {
webView.loadUrl("file:///android_asset/index.html");
}
});
return jsonResponse;
}
}
might not be a good approach but atleast its working :-)
Thanks

How do I download HTML of a website periodically and use it in my webview android?

I am making an app that has to display the content of a website.
I created my website I want to use and it will be responsive so that it works with different devices.
The question is how do I download the html code of my website periodically (once a day) and display the downloaded html files in my webview.
the [page will contain only a simple table that I will regularly update online.
I would like if you could tell me the steps to achieve this?
Thank you in advance!
If it's not necessary to download the html code & display the updated, you can display the whole website by providing the url to webview, you only need to change the view of website for mobile devices & it will be reflected in the webview.
And if this is not the thing you want then you need to perform webservice call which in return provide you JSON String, parse it into local string & replace the html code.
public class Main extends Activity {
private WebView mWebview ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
});
mWebview .loadUrl("http://www.google.com");
setContentView(mWebview );
}
}

Android WebView loading part of a website

Some websites have comments portion and many other unnecessary portions. I want to just display the main article excluding the other portions in my custom Android WebView.
I have tried the example from Display a part of the webpage on the webview android
But it still shows the full website.
There is also the loaddatawithbaseurl class in Android but it is not working too as you can't specify till which portion of a website to show using this class.
Is there any other way to do this?
Here it is with some changes...
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url)
{
String javaScript = "javascript: var form = document.getElementsByClassName('university_corner');"
+ "var body = document.getElementsByTagName('div');"
+ "body[0].innerHTML = form[0].innerHTML";
webView.loadUrl(javaScript);
}
});
webView.loadUrl(url);

Categories

Resources