Why does WebView.evaluateJavascript() remove escape characters?

风流意气都作罢 提交于 2019-12-24 09:58:32

问题


I have a stringified JSON object that I want to pass into my WebView as a string. If my JSON string is a simple one-level JSON like this:

JSONObject object = new JSONObject;
object.put("key1", "val1");
object.put("key2", "val2");
String myValue = object.toString();

And I run evaluateJavascript like this:

webView.evaluateJavascript("console.log('" + myValue + "')", null)

Then the console log I get is this:

{"key1": "val1", "key2", "val2"}

Which is correct.

But if my JSON has a sub JSON inside it, then the stringified version of that JSON should have escaped quotes in it for that inner JSON. So if I did this:

JSONObject object = new JSONObject();
object.put("key1", "val1");
JSONObject innerObject = new JSONObject();
innerObject.put("key3","val3");
object.put("key2", innerObject);
String myValue = object.toString();

And run the same evaluateJavascript statement above, I get the following console log

{"key1":"val1", "key2": "{"key3": "val3"}"}

Which is not what I am expecting! I'm expecting an output like this:

{"key1":"val1", "key2": "{\"key3\": \"val3\"}"}

The quotes of the inner JSON are supposed to be escaped. If they are not escaped, then trying to run a JSON.parse on it will result in a parse error.

I even used a debugger to inspect the run time value of myValue just before it is passed into evaluateJavascript and it looks the way it's supposed to:

"{"key1":"val1", "key2": "{\"key3\": \"val3\"}"}"

So why does running evaluateJavascript mysteriously strip away those explicit escape symbols?

NOTE:

The only way I could solve this was to run the following statement just before evaluateJavascript

myValue.replace("\\", "\\\\")

That is, replacing any escape characters (\) with 2 escape characters (\\). That way, the mysterious stripping will remove one escape character but leave the other one there which allows me to successfully JSON.parse it.


回答1:


You can use URLEncode to encode the contents while using javascript interface.

URLEncoder.encode(contents, "UTF-8");

And then for getting back the actual contents in js you can use

decodeURIComponent(contents.replace(/\+/g, '%20'));


来源:https://stackoverflow.com/questions/50583609/why-does-webview-evaluatejavascript-remove-escape-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!