Android webview javascript not working with loadDataWithBaseUrl

I am trying to upload data to android webview using

webview.loadDataWithBaseURL("", htmlcontent, "text/html", null, ""); 

The method returns an htmlContent from a StringBuilder that fills the html data.

I turned on javascript and installed webChromeClient as follows

 webview.getSettings().setJavaScriptEnabled(true); webview.setWebChromeClient(new WebChromeClient()); webview.addJavascriptInterface(new JSClass(), "Android"); 

my javascript interface:

 class JSClass { public void getHTMLContent(String html) { Log.i(Global.TAG, "HTMLContentReceived: "+html); } } 

and my javascript on the 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 javascript does not return any value. It works fine with loadData (url), where url is a simple web page in the resource folder

Please help Thanks in advance

+4
source share
1 answer

You have no baseURL to use, since you are loading dynamically generated HTML. For this reason webview.loadData(htmlcontent, "text/html", null); should be more than enough.

Javascripts does not throw any exceptions in Java code. Remember that JS is not text safe / strict as Java code ... My way is to put logs between sensitive Javascript calls to see if this line passes and check the values. Since you did not provide HTML, I would install WebChomeClient and override 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 then call, for example: console.log('check my value:' + (ele != null)) . Read more about it here .

Looking at the JavaScript code, I cannot figure out at what points this.innerHTML .

+1
source

Source: https://habr.com/ru/post/1487207/


All Articles