I’m attempting to pass the contents of a file into a Webview. Using the debugger I know that fileContents correctly contains the contents of the file, and that the file is read correctly. However, I’m getting a JavaScript ‘EOF’ error within the webview. Does the text need to be escaped or encoded before I pass it into the webview? Could newline characters within fileContents be disrupting stringByEvaluatingJava…?
//get file contents
NSStringEncoding *encoding;
NSError *error;
NSString *fileContents = [NSString stringWithContentsOfFile:path usedEncoding:encoding error:&error];
//trigger fileopen event and pass file contents into webview
NSString *event = @"fileopen";
NSString *extraJS = [NSString stringWithFormat:@"e.results='%@'",fileContents];
NSString *str = [NSString stringWithFormat:@"var e = document.createEvent('Events'); e.initEvent('%@', true, false); %@; document.dispatchEvent(e); ", event, extraJS];
[webView stringByEvaluatingJavaScriptFromString:str];
Edit (based on Hezi’s response):
NSString * result = [NSString stringWithFormat:@"e.result=decodeURIComponent('%@')",[results stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
[JSEventHelper triggerEvent:@"load" withExtraJS:result forWebView:self.webView];
Seems very weird that the above works, but it does!
Try using NSString’s method
stringByAddingPercentEscapesUsingEncodingto encode your string before sending it to javascript.