在 iOS UIWebView 中评估 JavaScript 时出现“SyntaxError: Unexpected EOF”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11478324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:22:21  来源:igfitidea点击:

“SyntaxError: Unexpected EOF” when evaluating JavaScript in iOS UIWebView

javascriptiosjsonuiwebviewxamarin.ios

提问by Dan Abramov

I keep getting this error in JavaScript when trying to pass some JSON to a UIWebView:

尝试将一些 JSON 传递给 a 时,我在 JavaScript 中不断收到此错误UIWebView

SyntaxError: Unexpected EOF

语法错误:意外的 EOF

There is no line number or filename available in window.onerrorbut I've already checked all referenced files, and they are fine.

没有可用的行号或文件名,window.onerror但我已经检查了所有引用的文件,它们都很好。

I'm using MonoTouch EvaluateJavaScriptmethod which is equivalent to ObjC stringByEvaluatingJavaScriptFromString::

我正在使用 MonoTouchEvaluateJavaScript方法,它相当于 ObjC stringByEvaluatingJavaScriptFromString:

webView.EvaluateJavascript(
    "Viewer.init($('#page'), " + json.ToString() + ");"
);

It works just fine on “simple” JSON input but breaks at larger objects.
What could go wrong?

它在“简单”的 JSON 输入上工作得很好,但在较大的对象上会中断。
什么可能出错?

回答by Willster

Before passing an NSString to a UIWebView, be sure to escape newlines as well as single/double quotes:

在将 NSString 传递给 UIWebView 之前,一定要转义换行符以及单/双引号:

NSString *html = @"<div id='my-div'>Hello there</div>";

html = [html stringByReplacingOccurrencesOfString:@"\'" withString:@"\\'"];
html = [html stringByReplacingOccurrencesOfString:@"\"" withString:@"\\""];
html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\n"];
html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];

NSString *javaScript = [NSString stringWithFormat:@"injectSomeHtml('%@');", html];
[_webView stringByEvaluatingJavaScriptFromString:javaScript];

回答by Dan Abramov

Apparently, I forgot to escape newlines in JSON, and thus created an “unexpected EOF” for?UIWebView.

显然,我忘记在 JSON 中转义换行符,因此为?UIWebView 创建了一个“意外的 EOF”。