Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 721
Dan Abramov Avatar asked Jul 13 '12 21:07

Dan Abramov


2 Answers

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];
like image 162
Willster Avatar answered Nov 01 '22 03:11

Willster


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

like image 6
Dan Abramov Avatar answered Nov 01 '22 03:11

Dan Abramov