Running Javascript in WebView when using LoadData - java

I am very new to Android Dev and I am developing what I thought would be a simple app. I have some HTML code that is stored is the raw resources folder - the code includes some Javascript. When I run the code in Google Chrome it runs fine - however when I load it into the webview using the loadData function it doesn't run the Javascript.
I have enabled javascript with:
mWebView.getSettings().setJavaScriptEnabled(true);
I need to be able to run this Javascript within the browser - any help?

Try this:
webView.loadDataWithBaseURL("blarg://ignored", getData(), "text/html",
"utf-8", "");

Try call JS function from code. Like this:
mWebView.loadUrl("javascript:myFunction()");

What does the loaded HTML data look like? In my case, the raw HTML data I generated was in the format:
<html>
<head>
<style>..</style>
<script>..</script>
</head>
<body>...</body>
</html>
Testing in a normal browser, things worked as expected. However, once I had used WebView.loadData, the CSS seemed to be recognized but I found that the Javascript was not working.
What found that worked for me was moving the Javascript to external files (more specifically I put the scripts I needed to assets/ using content providers.
<html>
<head>
<link rel="stylesheet" type="text/css" href="content://PATHTOSTYLESHEET" />
<script src="content://PATHTOJS"></script>
</head>
<body>...</body>
</html>
According to What is the difference between Android webview's loadData and loadDataWithBaseURL it sounds even more simple if you set a proper base URL which your style/scripts are stored - using the appropriate file:// for anything you store locally.

I am following up on #Cobaia's answer above, with another (I think) useful feature:
Since I need to keep changing the embedded HTML while testing and debugging, I decided to grab the raw page from my local web server during the development of the page and pass it to the webView as follows:
String url, str;
str = getFromURL(url);
webView.loadDataWithBaseURL("blarg://ignored", str, "text/html", "UTF-8", "");
where getFromURL() is defined as:
public String getFromURL(String urlToRead) {
URL url;
HttpURLConnection conn;
BufferedReader rd;
String result = "";
char[] chunk = new char[8192];
int blen = chunk.length;
int amt;
try {
url = new URL(urlToRead);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((amt = rd.read(chunk, 0, blen)) > 0) {
result += new String(chunk, 0, amt);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Note that I had to create a special controller (I'm using CodeIgniter) to allow downloading the file as a text file from the server.
Hope this hint helps others too!

The above solutions did not work for me because I was loading a string that held the HTML instead of a separate HTML file. The HTML in the string referenced JavaScripts that were in assets/www/. What worked was to use mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);
See below for a full example. The example create a webview, loads the HTML from the string, and then calls a function in a separate JavaScript file. The function simply shows an alert.
public class MainActivity extends Activity{
private WebView mWv;
private static final String HTML_AS_STRING =
"<!DOCTYPE html>" +
"<html>" +
"<head>" +
"</head>" +
"<body>" +
"<p>Just some text in a paragraph.</p>" +
"<div align=\"center\" style=\"color:#0000FF\">" +
"<h3>This is a heading in a div element</h3>" +
"<p>This is some text in a div element.</p>" +
"</div>" +
"<font size=\"4\" color=\"0000FF\">" +
"This is some sized and colored text." +
"</font>"
+
"<script src=\"index.js\"></script>" +
"</body>" +
"</html>";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mWv = (WebView)findViewById(R.id.webview);
mWv.getSettings().setJavaScriptEnabled(true);
mWv.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url){
mWv.loadUrl("javascript:showAlert()");
}
});
mWv.setWebChromeClient(new WebChromeClient());
mWv.loadDataWithBaseURL("file:///android_asset/www/", HTML_AS_STRING, "text/html", "UTF-8", null);
}
}
index.js (A separate file in assets/www/):
function showAlert() {
alert("A simple alert!");
}

Related

Grab IMG source from HTML link

I have this HTML code that I took from IMDB.
<img alt="Johnny Depp" height="209" src="https://m.media-amazon.com/images/M/MV5BMTM0ODU5Nzk2OV5BMl5BanBnXkFtZTcwMzI2ODgyNQ##._V1_UY209_CR3,0,140,209_AL_.jpg" width="140">
My question is how can I get the link of the image with <img src=,so the result will be:
"<img src="https://m.mediaamazon.com/images/M/MV5BMTM0ODU5Nzk2OV5BMl5BanBnXkFtZTcwMzI2ODgyNQ##._V1_UY209_CR3,0,140,209_AL_.jpg">
Thanks !
For parsing or scraping from URL, you need to add JSoup library.
Add the dependency in your gradle file.
implementation 'org.jsoup:jsoup:latest_version'
Then you can write a method to connect and get the HTML code.
private String getHTMLCode() {
try {
Document doc = Jsoup.connect("http://www.yourURL.com/").get();
Element imageElement = document.select("img").first();
String absoluteUrl = imageElement.absUrl("src"); //absolute URL on src
String srcValue = imageElement.attr("src"); // exact content value of the attribute.
} catch (IOException e) {
//For getting error print error in LOG
Log.d(TAG, e.getLocalizedMessage());
Log.e(TAG, "Failed to load HTML code", e);
Toast.makeText(this, "Failed to load HTML code",
Toast.LENGTH_SHORT).show();
}
}
For further documentation you can get help from the official site.

No Preview available when I load without .pdf content webview

I try to load my contant as PDF in webview android but it display No Preview Available How can i solve
My Code is Here :-
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.setWebChromeClient(new WebChromeClient());
String URLPATH = "http://myaccount365.in/public/oddeve78/report/ledger/11/summaryLedger?fromDate=01/11/2019&toDate=09/12/2019";
String url = "https://docs.google.com/gview?embedded=true&url=" + URLPATH;
webview.loadUrl(url);
The problem is clearly this:
You have two URLs - the URL of the PDF and the URL of google docs. Since you want to pass one URL to the other URL as a GET parameter (?embedded=true&url=) and the URL that you try to pass contains GET parameters as well: ?fromDate= and &toDate=, the seconds URL has to be URLEncoded.
So please just call
String url = "https://docs.google.com/gview?embedded=true&url=" + URLEncoder.encode(URLPATH, "ISO-8859-1");
and try again.
Caution: when working with URLEncoder.encode: you always have this problem: you can either call the #Deprecated method URLEncoder.encode(String s) without a specific encoding or the preferred method with URLEncoder.encode(String s, String enc) where you can specifiy the encoding, but this method has throws UnsupportedEncodingException in its signature :-O
Anyhow, both URLEncoder.encode(url) and URLEncoder.encode(url, "UTF-8") or URLEncoder.encode(url, "ISO-8859-1") will yield the same result since you have no UTF-8 or ISO-8859-1 specific characters in the URL:
https://docs.google.com/gview?embedded=true&url=http%3A%2F%2Fmyaccount365.in%2Fpublic%2Foddeve78%2Freport%2Fledger%2F11%2FsummaryLedger%3FfromDate%3D01%2F11%2F2019%26toDate%3D09%2F12%2F2019
I'm using this and works for me: Check Here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView webView=new WebView(MainActivity.this);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
//---you need this to prevent the webview from
// launching another browser when a url
// redirection occurs---
webView.setWebViewClient(new Callback());
String pdfURL = "http://www.expertagent.co.uk/asp/in4glestates/{16D968D6-198E-4E33-88F4-8A85731CE605}/{05c36123-4df0-4d7d-811c-8b6686fdd526}/external.pdf";
webView.loadUrl(
"http://docs.google.com/gview?embedded=true&url=" + pdfURL);
setContentView(webView);
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(
WebView view, String url) {
return(false);
}
}
OR Try
I think Exact Problem is in URL encoding which we concat with "http://docs.google.com/gview?url=". This means we have to replace all special character(:, /, & etc) of url with unicode. Uri.encode("") do the trick for us.
Like this
String url = Uri.encode("your link");
String finalUrl = "http://docs.google.com/viewer?url=" + url + "&embedded=true";
I think it is your pdf file URL problem, please check your URLPATH it wether return a pdf URL like this https://www.tutorialspoint.com/css/css_tutorial.pdf
I use this URL it render normal
String URLPATH = "https://www.tutorialspoint.com/css/css_tutorial.pdf";
String url = "https://docs.google.com/gview?embedded=true&url=" + URLPATH;
//url:https://docs.google.com/gview?embedded=true&url=https://www.tutorialspoint.com/css/css_tutorial.pdf
webview.loadUrl(url);
I think your URLPATH is a dynamic url, it return a file url according to the params. but now it may be not return a correct url. it can to check it, or you change the URLPATH to a url which has http://host:port/path/.pdf . use it to test your code.
String URLPATH = "http://www.pdf995.com/samples/pdf.pdf";
String url = "https://docs.google.com/gview?embedded=true&url=" + URLPATH;
webview.loadUrl(url);

Android WebView onPageFinished BUG

After update API (27) in Android OREO this code is no longer working:
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:(function() {document.getElementById(\"imPage\").style.display='none';})()");
}
I have also tried with:
webView.loadUrl(
"javascript:(function() { " +
"document.addEventListener(\"DOMContentLoaded\", function(event) {" +
"document.getElementById(\"imPage\").style.display='none';" +
"});" +
"})()");
Element not hiding and debug return:
I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'style' of null", source: mywebsite/ (1)
So I think the javascript is injected before loading page, this explains why the line is 1, because I have other code called after loading page is finished but this code is called when page is white, not loaded.
In my own project I have been using evaluateJavascript(script,null) in onPageFinished to hide html elements. view.loadUrl() Should work the same way.
If you don't need the function be called at later time you could simplify your JS string and instead of \" try using '.
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:document.getElementById('imPage').style.display='none';");}
document.getElementById(\"imPage\") must be returning null.
So there is either no imPageelement or you haven't loaded the page at the time.
I would suggest moving your entire js code into
document.addEventListener("DOMContentLoaded", function(event) {
//insert here
});
You have to enable Javascript Seetings like below :-
view.getSettings().setJavaScriptEnabled(true); //Yes you have to do it

export to excel from web application is not working

I am having a very wierd issue and I'm hoping you can help me out
At work, we use a web application made with the framework GWT, and all the sales reports have an option to export the data to excel. It usually works fine, but the days that the report has more than about 15-20 thousand rows, the excel file only opens with the word "null" on the first cell.
Within the code, we use a JSP to send the data as html and a StringBuffer object to append all the text of the html. Here es the method that sends the html:
public void export(final String psFormat) {
manageStartOfCall();
String lsFileName = "resources/system/excel_file.jsp";
final DynamicForm loForm = new DynamicForm();
loForm.setAction(lsFileName);
loForm.setMethod(FormMethod.POST);
loForm.setCanSubmit(true);
final TextAreaItem loDataToExport = new TextAreaItem("psExcelData");
final Window loExcelWindow = new Window();
loExcelWindow.setWidth(5);
loExcelWindow.setHeight(5);
loExcelWindow.addItem(loForm);
addChild(loExcelWindow);
new Timer() {
public void run() {
cancel();
loDataToExport.setValue(moHeader.getHeaderAsExcel() + "<br><br>" + moReportGrid.getDataAsHTML());
loForm.setFields(loDataToExport);
new Timer() {
public void run() {
cancel();
manageEndOfCall();
loForm.submit();
loExcelWindow.destroy();
}
}.schedule(200);
}
}.schedule(200);
}
I've already debugged the getDataAsHTML method and the string that it returns is fine, it contains the correct HTML, however when I call the method getParameter in the JSP y returns a null value. Here the code of the JSP:
<%
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=eYumReport.xls");
String msDataToExcel = request.getParameter("psExcelData");
%>
<html>
<head>
<title>Data to excel</title>
</head>
<body>
<%=msDataToExcel %>
</body>
</html>
I may have to mention I am using this on Firefox 26, GWT 2.1, smartGWT 2.4, Windows 7 Professional and the Web application is on Windows Server 2008, mounted on Apache 6.
Any ideas why this is happening??

Load all resources through a proxy in webview android

How can i load resources dynamically from an android webview using onLoadResource() callback from a webviewClient?
Below is the code i have written so far. when i get new resources, it loads for example, the whole page of one single imagine instead of updating and displaying the image on the same original url of the webpage.
If a webpage has 5 images and text, my current code will load 5 pages each time onLoadResource tries to load an image.
what i want it to do is to load the images in the same page and any other resources as well such as JS, jquery's etc.
#Override
public void onLoadResource(WebView view, String url) {
addRequestToProxy(url);
}
public void addRequestToProxy(String url){
//pass url to proxy and wait for respoonse
String response;
//handle response
if(mime-type == IMAGE){
String urlStr = "http://example.com/my.jpg";
String pageData = "<img src=\"data:" + contentResponse.getMimeType()
+ ";base64," + contentResponse.getContent() + "\" />";
mWebView.loadDataWithBaseURL(urlStr, pageData, "text/html", null,
urlStr);
}else{
mWebView.loadDataWithBaseURL(null, response, "text/html", null,
null);
}
Instead of overriding onLoadResource() it's better to do it this way - shouldInterceptRequest()
webview shouldInterceptRequest example

Categories