android webview javascript not working with loadDataWithBaseUrl - javascript

I am trying to load data into android webview using
webview.loadDataWithBaseURL("", htmlcontent, "text/html", null, "");
a method returns htmlContent from a StringBuilder which populates html data.
I have enabled javascript and set webChromeClient as follows
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebChromeClient(new WebChromeClient());
webview.addJavascriptInterface(new JSClass(), "Android");
my interface to javascript:
class JSClass {
public void getHTMLContent(String html)
{
Log.i(Global.TAG, "HTMLContentReceived: "+html);
}
}
and my javascript in html page:
<script type="text/javascript">
var ele = document.getElementsByClassName('test');
for(var i=0;i<ele.length;i++){
ele[i].onclick = function(){
window.Android.getHTMLContent(this.innerHTML);
}
}
</script>
but somehow the javascript is not returning any value.
It works fine with loadData(url) where url is a simple webpage in assets folder
Please help
Thanks in advance

You don't have any baseURL to use, since you're loading a dynamical generated HTML.
For this reason webview.loadData(htmlcontent, "text/html", null); should be more than enough.
Javascripts don't throw any exceptions in Java code. Remember that JS is not that type-safe/strict as Java code ... My way of doing is to put logs between sensitive Javascript calls to see if that line passes and to check values. Since you didn't provide the HTML, I would setup the WebChomeClient and override the onConsoleMessage:
webview.setWebChromeClient(new MyChromeClient());
private class MyChromeClient extends WebChromeClient {
#Override
public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
String message = consoleMessage.message() + " -- line " + consoleMessage.lineNumber();
switch (consoleMessage.messageLevel()) {
case ERROR:
logErrorMessage(message);
break;
default:
logInfoMessage(message);
break;
}
return true;
}
private void logInfoMessage(String message) {
Log.i("JSTag", message);
}
private void logErrorMessage(String message) {
Log.e("JSTag", message);
}
}
From your JavaScript you would then call for example: console.log('check my value:' + (ele != null)). More info on this here.
Looking at your JavaScript code, I can't understand to what points this.innerHTML.

Related

Passing value from java to Javascript

I'm making an Android app using webview.
The app can print out receipts. What I want to do is when the printer is not working, alert box shows up to tell the printer isn't working, and return false to the form's onsubmit event to prevent form from being submitted.
Java code:
public class JSKicker {
#JavascriptInterface
public void callPrint(final String argumet) {
Thread thread = new Thread(new Runnable() {
public void run() {
int nRtn;
connectionNum = myPrinter.Connect("000.000.0.000");
if(connectionNum < 0){ //Printer not working
webview.post(new Runnable() {
#Override
public void run() {
String script = "alert('Printer Error'); return printer_connection = false;";
webview.evaluateJavascript(script, new ValueCallback<String>() {
#Override
// I can't figure out what to do here...
});
}
});
}else{ //Printer is working properly
connectionNum = myPrinter.SetLocale(8);
strText = argument;
nRtn = myPrinter.PrintText(strText, "SJIS");
nRtn = myPrinter.PaperFeed(64);
nRtn = myPrinter.CutPaper(1);
myPrinter.Disconnect();
}
}
});
thread.start();
}
JavaScript in header:
<script type="text/javascript">
function gate(){
jQuery.ajax({
url:'/cart_info.php',
type:'GET'
})
.done( (data) => {
window.JSKicker.callPrint(data);
})
if (printer_connection = false) {
return false;
}else{
return true;
}
}
</script>
HTML form tag:
<form method="post" id="order_form" onsubmit="return gate();">
How can I get this work?
Could you do it thru WebView.evaluateJavascript()?
https://developer.android.com/reference/android/webkit/WebView.html#evaluateJavascript(java.lang.String,%20android.webkit.ValueCallback%3Cjava.lang.String%3E)
So with that you could send simple CustomEvent to document in WebView
webView.evaluateJavascript("document.dispatchEvent(new Event('printer_error', { details: "No printer found!" }));");
and in JavaScript you can hook listener for your custom event to react.
document.addEventListener('printer_error', e => alert(e.details));
Didn't test this so might be that at least evaluateJavascript() needs callback function.
WebSocket can solve your problem.
WebSockets provide a persistent connection between a client and server that both parties can use to start sending data at any time. The client establishes a WebSocket connection through a process known as the WebSocket handshake.
Its very straight forward and easy to implement.
You can follow referrer links for more details:-
JAVA WebSocket:- WebSocket using Spring Boot, WebSocket using Simple JEE
Browser WebSocket(JavaScript):- WebSocket API
In Android ,if you want webview pass value to JavaScript.
First,you need to set the webview enable the JavaScript,
private WebView mWebView;
void onCreate(){
mWebView = findViewById(R.id.webview);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(false);
}
And ,in you want do some thing code
if(connectionNum < 0){ //Printer not working
// I need to do something here to send a message that the printer isn't working to JS.
//In thread can not use mWebView,should send message to MainThread to do
// mWebView.loadUrl("javascript:javaCall()");
Message msg = new Message();
msg.what = 1;
myHandler.sendMessage(msg);
//myHandler can be your MainThread send to here
}
And where the mWebView created in your code, be in main thread ,you can use the
Handler to deal with the message sended to here.
private Handler myHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// this 1 is just thread send to here
if (msg.what == 1) {
//and here can do the webview UI method
mWebView.loadUrl("javascript:javaCall()");
}
}
};
the javaCall() is where you JacaScript invoke method,in javaScript you can writre like this:
<script language="javascript">
function javaCall(){
alert("Printer Error");
//other thing you can do
}
</script>
if you have problem ,you can refer to the official document.
public void loadUrl (String url)
Loads the given URL.
Also see compatibility note on evaluateJavascript(String, ValueCallback).
webview use link

How to call java script function from ashx handler file

My function
<script type="text/javascript">
function methodtocall(id) {
// My code
}
</script>
My ashx page
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
// here i need to call that method
}
}
yes i referred net.But no solutions for that. mostly they give solution to call from method to ashx or call from ajax.
can anyone direct me with correct thing?
Refer like this,
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", script, true);
as per code,
public class sampleClass : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
var id = "someid"; //implement the id that you want to pass to the Javascript function
ClientScript.RegisterStartupScript(this.GetType(), "methodtocall", id, true);
}
}
Hope this helps..!
reference Link : Link
you can do like this
context.Response.Write("<script type='text/javascript'>function closeCurrentTab(){var conf=confirm('Are you sure, you want to close this tab?');if(conf==true){close();}}</script>");
context.Response.Write("<script type='text/javascript'>closeCurrentTab();</script>");

How to scrape Javascript template in Htmlunit?

How to scrape 'handlerbars.js' javascript template in htmlunit 2.21? I try to execute this, but this message shown:
'text/x-javascript-template' is not javascript.
and script does not execute. I execute command page.asXml().
Output text is nothing. Do you know dependency for execute javascript template in Htmlunit? Please help.
This Code
HtmlUnit Config
webClient = new WebClient(BrowserVersion.CHROME);
webClient.getBrowserVersion().setBrowserLanguage("ko-kr");
ConfirmHandler okHandler = new ConfirmHandler() {
#Override
public boolean handleConfirm(Page page, String message) {
logger.info("[Confirm] " + message);
return true;
}
};
AlertHandler alertHandler = new AlertHandler() {
#Override
public void handleAlert(Page page, String message) {
logger.info("[Alert] " + message);
}
};
webClient.setRefreshHandler(new ImmediateRefreshHandler());
webClient.getOptions().setGeolocationEnabled(true);
webClient.getOptions().setRedirectEnabled(true);
webClient.getOptions().setUseInsecureSSL(true);
webClient.getOptions().setCssEnabled(false);
webClient.getOptions().setJavaScriptEnabled(script);
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setThrowExceptionOnScriptError(false);
webClient.getOptions().setTimeout(0);
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.setConfirmHandler(okHandler);
webClient.setAlertHandler(alertHandler);
page move code
page = webClient.getPage("https://promotions.expediapartnercentral.com/promotions/manageroomandrate.html?htid=" + siteIdx);
webClient.waitForBackgroundJavaScript(1000);
page.asXml() repsonse is empty(script is not execute)

The HTML with javascript is not getting loaded in android webview

I am trying to display a page containing HTML with javascript in android webview with the below code.But this doesn't seem to work.Can anyone help me out.
public class MainActivity extends ActionBarActivity {
WebView browser;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
browser = (WebView) findViewById(R.id.webView);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
loadTime();
}
void loadTime() {
String page = "<html>"
+"<head>"
+"<title>chat window</title>"
+"<script type=\"text/javascript\">"
+ "var bccbId = Math.random(); document.write(unescape('%3Cdiv id=' + bccbId + '%3E%3C/div%3E'));"
+" window._bcvma = window._bcvma || [];"
+" _bcvma.push([\"setAccountID\", \"423771628801258096\"]);"
+" _bcvma.push([\"setParameter\", \"WindowParameters\", \"vr=&vi=&ve=" + gblQnbVars["gUserEmail"] + "&vp=" + gblQnbVars["gMobileNum"] + "&vn= "+ gblQnbVars["gCustomerFirstName"]+ "&lc=\"]);"
+"var bcLoad = function(){"
+ " if(window.bcLoaded) return; window.bcLoaded = true;"
+" var vms = document.createElement(\"script\");"
+"vms.type = \"text/javascript\";"
+" vms.async = true;"
+" vms.src = ('https:'==document.location.protocol?'https://':'http://') + \"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
+"var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(vms, s);"
+"};"
+"if(window.pageViewer && pageViewer.load) pageViewer.load();"
+" else if(document.readyState==\"complete\") bcLoad();"
+" else if(window.addEventListener) window.addEventListener('load', bcLoad, false);"
+" else window.attachEvent('onload', bcLoad);"
+ "function FireBoldChat() {"
+" try {"
+ " _bcvmw.chatWindow({"
+ "type: \"chat\","
+ "rdid: \"\","
+ "cwdid:\"1504531236710990857\","
+ "ve:\"<%=visitor email%>\","
+ "vp:\"<%=visitor phone%>\","
+ "vn:\"<%=visitor name%>\","
+ "embed: true"
+ "});"
+" } catch (e) {"
+"setTimeout(FireBoldChat, 500)"
+" }"
+" };"
+" </script>"
+"</head>"
+"<body onload=\"FireBoldChat();\">"
+"</body>"
+"</html>";
System.out.println(page);
browser.loadDataWithBaseURL("x-data://base", page,
"text/html", "UTF-8",
null);
}
private class Callback extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
loadTime();
return(true);
}
}
Whenever I load my this webpage in default browser its working perfectly. Where i have did wrong.
The documentation for loadData() says
Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.
Now you do use loadDataWithBaseURL(), but your base URL is x-data://base yet you try to load a script from http(s)://vmss.boldchat.com. I think that can cause your problem.
I got same problem. I just replace
vms.src="https://" +\"vmss.boldchat.com/aid/423771628801258096/bc.vms4/vms.js\";"
this will be come if not add necessary java script file
before run please check your XML format is ok
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
for more :http://developer.android.com/guide/webapps/webview.html
and you may not call layout
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_main);
WebView webView = (WebView)
browser = findViewById(R.id.webview);
browser.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
browser.setWebViewClient(new Callback());
browser.getSettings().setJavaScriptEnabled(true);
}
}
try this some time this will be help
thank
Looking at your code, didn't see the run time changes in html file.
So create html file using above page variable & put in assets folder.
once this done write following code:
public class ViewWeb extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
WebView vistaWeb = (WebView) findViewById(R.id.webView1);
vistaWeb.setWebChromeClient(new Callback());
vistaWeb.setWebViewClient(new Callback());
vistaWeb.clearCache(true);
vistaWeb.clearHistory();
vistaWeb.getSettings().setJavaScriptEnabled(true);
vistaWeb.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
vistaWeb.loadUrl("file:///android_asset/aboutcertified.html"); // now it will not fail here
}
}
Hope this will help you.
I suspect the variable gblQnbVars I did not find any reference to it in your snippet. Can you confirm if it is accessible in your code? May be that's throwing error.

Android: Android 4.4.4 WebView upload image, but JavaScript check file type error

I use Android WebView to show a web server's web page in Android 4.4.4.
But at the server side, JavaScript check for the image file type fails. So I cannot upload my image.
But without changing the server side code, I can upload image successfully in iOS WebView and on desktop using the same image file.
The following is my Server side JavaScript image checker code
var check_file = function (file) {
if (file.size > 1048576 * 10) {
upload_err_hdlr(413);
return false;
}
alert("Before Check");
if (!file.type.match(/image\/(jpeg|png|gif|jpg)/)) {
alert("Check fail");
upload_err_hdlr(415);
return false;
}
alert("Check successfully");
return true;
};
after I upload the image via Android 4.4.4 WebView, it shows an alert dialog
1. Before Check
2. Check fail
The following is my Android code
public class MainActivity extends Activity {
private static final int FILE_CHOOSER_RESULT_CODE = 1;
WebView mWebView;
private ValueCallback<Uri> mUploadMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new CustomWebViewClient());
mWebView.setWebChromeClient(new WebChromeClient() {
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUploadMessage = uploadMsg;
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, FILE_CHOOSER_RESULT_CODE);
}
});
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
CookieManager.setAcceptFileSchemeCookies(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
mWebView.loadUrl("http://192.168.1.30:5000/dashboard");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if(requestCode == FILE_CHOOSER_RESULT_CODE) {
if(mUploadMessage == null)
return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
Log.d("Ting", "after result:" + result);
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
private class CustomWebViewClient extends WebViewClient {
}
}
The Android log "Ting" shows:
02-02 11:44:14.782 12456 12456 D Ting : after result:content://media/external/images/media/12255
The Uri is content://media/external/images/media/12255
This is the uploaded fail image
Anyone has any idea?
Thanks in advance.
Eric
======================
Additional Information:
I print the file content in JavaScript.
alert(JSON.stringify(file));
And the shows
{"webkitRelativePath":"","lastModified Date":"2015-01-17T10:04:30.000Z","name":"12255","type":"","size":2369496}
It seems that the uploaded image file has no "type" attribute.
Anyone knows why?
Thanks.
it's because file type isn't supported in Mobile browsers ,
check File type Support
You can try to check the file type using Regular expression :
if((/\.(gif|jpg|jpeg|tiff|png)$/i).test("filename")) {
// the file is an image
} else {
//file type is different than (JPEG,PNG,GIF,TIFF)
}

Categories