最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

SyntaxError: Unexpected EOF

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

I'm using MonoTouch EvaluateJavaScript method which is equivalent to 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?

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

SyntaxError: Unexpected EOF

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

I'm using MonoTouch EvaluateJavaScript method which is equivalent to 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?

Share Improve this question edited May 23, 2017 at 12:18 CommunityBot 11 silver badge asked Jul 13, 2012 at 21:01 Dan AbramovDan Abramov 268k86 gold badges416 silver badges518 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 30

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

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];

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

发布评论

评论列表(0)

  1. 暂无评论