How to display image from javascript in Android web view - android

I want to display content from remote URL in android web view, which will be return by java script tag. In my case , java script tag return image , which should be load into web view.
Here is code to render image/content from remote URL.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
String customHtml = "<script src='http://mytestdomain.com/test.php?w=300&h=250' type='text/javascript'></script>" ;
webView.loadData(customHtml, "text/html", "UTF-8");
}
URL load the content but image are broken and do not display properly. Though i can click on on the image and land into correct link.
I have proper permission
<uses-permission android:name="android.permission.INTERNET"/>
How can i fix it. Any help is appreciate.

I think the issue is with your js code. I tried this code and image is showing fine.
<html>
<body>
<h3>A demonstration of how to access an IMG element</h3>
<img id="myImg" src="http://via.placeholder.com/350x150" alt="The Pulpit Rock" width="304" height="228">
<p>Click the button to get the URL of the image.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("myImg").src;
document.getElementById("demo").innerHTML = x;
}
</script>
</body>
Also enable DomStorage:
webView.getSettings().setDomStorageEnabled(true);

Broken image issue because presence of protocol-relative url (//) for the image returned by our server. These kind of URLs (//:mytestdomain.com) will force the protocol to be the same as it's parent page, and the app's web view might be missing a base scheme for the image to inherit. I placed proper protocol into url and it working fine now

Related

WebView : setCookie to show a private image inside custom html

I have the following image.
http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG
It is a private path so a valid cookie is needed to get it.
So I am using this code to show it in my webView:
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(myWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://example.com",cookie);
cookieSyncManager.sync();
String getcookie = cookieManager.getCookie("http://example.com");
MyLog.myLog("getcookie "+getcookie);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebChromeClient(new WebChromeClient());
myWebView.loadUrl("http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG");
It works fine. I can see the image correctly. So I guess the cookie code is working.
Now I need to show the image inside a custom html file (privateimage_test.html):
.....
.....
<div>
<img src="http://example.com/system/files/private/fd41dbdea705d275aa2f5cf09c33731732f82c6d11c1951c5faa570059d52911989001fce5870053c0deeed85c028def20b18502108ad8d5d329ad007f45778c.JPG" style="width:100%">
</div>
.......
Now my java code is the same excepting the last line:
myWebView.loadUrl("file:///android_asset/privateimage_test.html");
In this case I am not seeing my image.
It works fine if I replace the private image with any public image in my html file. So I guess is a cookie problem.
Any help?
Thanks.
If you are trying to load an image from an html stored into /assets, remember that paths of that image must be defined as "file:///android_asset/..."
This is ok :
myWebView.loadUrl("file:///android_asset/privateimage_test.html");
but images defined into privateimage_test.html must have the path
<img src="file:///android_asset/html/<"Image file name">" >
If you have problems loading your image from the .html file stored in /assets
<div>
<img src="http://example.com/system/files/private/myimage.JPG" style="width:100%">
</div>
Remember to have defined the permission for access to internet.
<uses-permission android:name="android.permission.INTERNET"/>
Remember to use urls defined with https:// instead of http:// because you will have problems using Android 9+.

iframe "File not found" error

I don't know much about html but there is a small issue and I am unable to find its solution.
This is the iframe that I want to display on static html page:
<!DOCTYPE html>
<html>
<body>
<iframe style="width:120px;height:240px; padding-right:50px; padding-bottom:50px" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=qf_sp_asin_til&ad_type=product_link&tracking_id=qstore51214-20&marketplace=amazon&region=US&placement=0553496670&asins=0553496670&linkId=4f9912a00b832e2f8bcb5a9b187511cf&show_border=true&link_opens_in_new_window=true&price_color=333333&title_color=0066c0&bg_color=ffffff">
</iframe>
</body>
</html>
When I add this to html and try to open html page, I get the error:
"File not found".
But when I add this iframe to any live html editor it work perfectly and show the link.
Actually I want to display this iframe in Webview in my Andriod application.
My android code is:
mWebViewTopSeller = (WebView) findViewById(R.id.webViewTopSeller);
mWebViewTopSeller.setWebChromeClient(new WebChromeClient());
mWebViewTopSeller.setWebViewClient(new WebViewClient());
mWebViewTopSeller.getSettings().setJavaScriptEnabled(true);
mWebViewTopSeller.loadUrl("file:///android_asset/TopSeller.html");
Please help. Thanks!
When embedding this iframe, it returns an error:
SEC7111: HTTPS security is compromised by https://ws-na...
So it may have something to do with the browser's mixed-content/same-origin policy.
Possible src values are an absolute URL that points to another web site (like src="http://www.example.com/default.htm")
or an relative URL that points to a file within a web site (like src="default.htm" I think your src path is wrong.

how can Send parameters to a local file in a WebView in android?

working on a native Android app. I am able to load a local file index.html into a WebView:
The web url loads fine. Now, I would like to load the web with some parameters, in the same way one types this in the browser:
So I can get those values inside the javascript of the html file. Is there any way to send parameters to a local html file?
html:
<input type="hidden" name="deviceid" id="deviceid"/>
i pass the device_id on local html file.
You can send them as get parameters while loading your html in WebView itself, and then later catch it in your JavaScript using window.location.href property. Something like this:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("/assets/index.html?foo=bar");
edit
To send the Device-ID, use the below code instead:
TelephonyManager tm=(TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
String did = tm.getDeviceId();
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("/assets/index.html?DeviceID=" + did);

Android WebView loadWithBaseURL

I am wondering how do I set the path for WebViews loadWithBaseURL correctly.
What I want to do is, to load html in a webview, that uses resources that are stored on the external storage.
For Example:
<html>
<head>
<style>body{ background-image:url(beach.jpg); }</style>
</head>
<body>
<img src="football.jpg" />
</body>
</html>
Where beach.jpg and ball.jpg are stored directly in the "root" directory of the phones external storage (/sdcard/beach.jpg and /sdcard/ball.jpg)
So I tried to load the content as follows:
String html = "<html> ... example from above ... </html>";
String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
webView.loadDataWithBaseURL("file://" + base, html, "text/html", "utf-8", null);
However the path seems to be wrong, because I can't see the image in the webview.
Any suggestions?
Have you enabled file access on the webview?
webView.getSettings().setAllowFileAccess(true);
Additionally, if you are constructing the HTML yourself - you might consider using full paths for the images.
String html = "<html>... <img src=\"file://"+base+"/football.jpg\" />";
Have you give internet permission?
<uses-permission android:name="android.permission.INTERNET" />
These may also help..
Android webview loadDataWithBaseURL how load images from assets?
http://myexperiencewithandroid.blogspot.com/2011/09/android-loaddatawithbaseurl.html
Android v2.2-2.3.5: WebView : loadDataWithBaseURL : will only load page once

JavaScript in a WebView

I have a block of html that has javascript embedded in it:
<!DOCTYPE html>
<html>
<body>
<h1>Testing</h1>
<script type="text/javascript">
var paEmbedId = 461745;
var paEmbedWidth = 600;
var paEmbedOemId = 24500;
var paServer = 'http://www.ncataggies.com/';
var paIframe = true;
</script>
<script type="text/javascript" src="http://www.ncataggies.com/oemjs/0/PhotoAlbum2009Embed.js"></script>
</body>
</html>
When I put the code inside a text document and run it from a browser(as a HTML file), the code runs perfectly.
How can I do this using a WebView in android?
You can use loadData method of WebView widget:
String summary = "<html><body>You scored <b>192</b> points.</body></html>";
webview.loadData(summary, "text/html", null);
// ... although note that there are restrictions on what this HTML can do.
// See the JavaDocs for loadData() and loadDataWithBaseURL() for more info.
If JS is not enabled, then you can also enable JS in WebView:
webview.getSettings().setJavaScriptEnabled(true);
But before that, you may want to read this from Android:
By default, a WebView provides no browser-like widgets, does not
enable JavaScript and web page errors are ignored. If your goal is
only to display some HTML as a part of your UI, this is probably fine;
the user won't need to interact with the web page beyond reading it,
and the web page won't need to interact with the user. If you actually
want a full-blown web browser, then you probably want to invoke the
Browser application with a URL Intent rather than show it with a
WebView.

Categories

Resources