简体   繁体   中英

android webview javascript not working with loadDataWithBaseUrl

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM