0

I want to pass multiple values from Android WebView to JavaScript. The Problem is, that the String i receive in JS is absolutely raw (like control characters showing in plain text).

So my specific problem is that i send the following String from Java:

final String chartData = "{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }";

And what i receive is absolutely raw:

"{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }"

But i want this (the java-parsed string):

{ "data": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }

I dont handle any JSON now, so you can ignore the "syntaxproblem" in the JSON string. I just want to receive the String correctly first. Here is my code so far:

WebViewActivity.java

webView = (WebView) findViewById(R.id.webView1);

    webView.getSettings().setJavaScriptEnabled(true);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setAllowUniversalAccessFromFileURLs(true);
    webSettings.setAllowFileAccessFromFileURLs(true);

    final String chartData = "{ \"data\": 1000, a: 10, b: 30, c: [ 5, 10, 15 ] }";

    webView.setWebChromeClient(new WebChromeClient());
    webView.setWebViewClient(new WebViewClient(){
        public void onPageFinished(WebView view, String url){
            webView.loadUrl("javascript:showAlert('message from android')");
            webView.loadUrl("javascript:createChart('"+chartData+"')");
        }
    });

    webView.loadUrl("file:///android_asset/report.html");

report.html

<div id="debugContainer">
    debug
</div>

script.js

function createChart(lineChartData){
document.getElementById('debugContainer').innerHTML = JSON.stringify(lineChartData, null, 4);}

1 Answer 1

1

What you receive is stringified JSON, you can JSON.parse() it to have it as a regular object or replace escaped characters. Msg sent through http is always a string. You need to either use a string or parse it to json.

Sign up to request clarification or add additional context in comments.

1 Comment

You're right. JSON.stringify() caused that. It was just a display problem. When i display the received JSON-string directly, the string looks like i expect it. So Json.parse() is the right choise like mentioned. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.