Can not push HTML block into the android html page

Viewed 46

I am getting a HTML block from server and want to push it into a html page in android application.

A sample html coming from server (this is the exact output with crlf etc. printed in logcat):

<ul>
   <li><a href="Details.html?id=tu&i=217">217</a></li>
   <li><a href="Details.html?id=tu&i=214">214</a></li>
</ul>

This is how I pass the output to the application html page:

runJavaScript("setHTML('"+ html +"')");


public void runJavaScript(final String code){
    webview.post(new Runnable() {
        @Override
        public void run() {
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                webview.evaluateJavascript(code, null);
            }else {
                webview.loadUrl("javascript:" + code);
            }
        }
    });
}

and this is the Javascript setHTML function inside the html page which is being called from android:

function setHTML(html){
    $("#result").html(html);
}

this is the error:

"Uncaught SyntaxError: Invalid or unexpected token", source: file:///android_asset/html/en/result.html (1)

I have tried debugging the project by replacing the HTML block with a simple word and it works. I think HTML characters like quotation or crlf may produce the error but I don't want to escape them (I dont want to set pure text but real html). How should I change current codes? thanks.

1 Answers

I guess, it's too late and doesn't answer your question exactly, as you don't want to escape any characters (I'm not sure why though), but maybe it will help somebody. In my case, before running runJavaScript("setHTML('"+ html +"')"); I had to escape all single quotation marks and it was enough.

html = html.replace("'", "\\'");

Related