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

Dan*_*mov 11 javascript json uiwebview xamarin.ios ios

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

SyntaxError:意外的EOF

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

我正在使用EvaluateJavaScript等同于ObjC的MonoTouch 方法stringByEvaluatingJavaScriptFromString::

webView.EvaluateJavascript(
    "Viewer.init($('#page'), " + json.ToString() + ");"
);
Run Code Online (Sandbox Code Playgroud)

它在"简单"JSON输入上运行得很好但在较大的对象处中断.
怎么可能出错?

Wil*_*ter 18

在将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];
Run Code Online (Sandbox Code Playgroud)


Dan*_*mov 5

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