为什么WebView.evaluateJavascript()删除转义字符? [英] Why does WebView.evaluateJavascript() remove escape characters?

查看:391
本文介绍了为什么WebView.evaluateJavascript()删除转义字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串化的JSON对象,我想将它作为字符串传递到WebView中.如果我的JSON字符串是像这样的简单一级JSON:

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();

然后我像这样运行evaluateJavascript:

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

然后我得到的控制台日志是这样的:

Then the console log I get is this:

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

那是正确的.

但是,如果我的JSON中包含一个子JSON,则该JSON的字符串化版本应在其中包含该内部JSON的引号.因此,如果我这样做:

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();

并运行与上面相同的evaluateJavascript语句,我得到以下控制台日志

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\"}"}

内部JSON的引号应该被转义.如果它们没有转义,则尝试在其上运行JSON.parse会导致解析错误.

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.

我甚至在将myValue的运行时值传递到evaluateJavascript之前,还使用了调试器来检查它的运行时间值,它看起来应该是这样的:

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\"}"}"

那么为什么运行evaluateJavascript会神秘地剥离那些显式的转义符号?

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

我能解决此问题的唯一方法是在evaluateJavascript

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

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

也就是说,将任何转义字符(\)替换为2个转义字符(\\).这样,神秘的剥离将删除一个转义字符,而将另一个转义字符保留在那里,这使我能够成功地JSON.parse.

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.

推荐答案

您可以在使用javascript界面​​时使用URLEncode对内容进行编码.

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

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

然后要获取js中的实际内容,您可以使用

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

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

这篇关于为什么WebView.evaluateJavascript()删除转义字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆