I have to do some complex work with a UIWebView and Javascript and always get problems when I try to insert complex Javascripts involving JQuery and HTML Snippets that contain JavaScript themselves. I never seem to have enough quote and single quote signs and putting in script elements is kinda painful.
I there a magic Objective-C snippet, or an easier copy-pasteable way of using more complex scripts that you use for such tasks?
EDIT: To explain a bit more, I have big snippets of HTML (containing also Javascript and stuff like <a href="javascript:doSomething('stupid')")> that I need to put in the DOM via JavaScript, after I load a website in an UIWebView.
My approach now is to put the HTML stuff into files, rewrite them so that I for example have 'stupid' in a JS-variable so I don't need additional single quotes, put placeholders into place like ###placeholder1###, load that file into an NSString and replace those placeholders by dynamic data generated in my app via html = [html stringByReplacingOccurrencesOfString:@"###placeholder1###" withString:dynamicStuffHtml];. The dynamic data before contains no single quotes, other than in the text-content, for which I replace the single quotes with the HTML-encoded '.
Then I try to put that whole string into the DOM by doing this:
NSString* javascript = [NSString stringWithFormat:@"%@%@%@",@"jQuery('.focus_box').first().before('",html,@"');"];
[webView stringByEvaluatingJavaScriptFromString:javascript];
This works for easy and short examples (for example when I put in short paragraphs or simple HTML), but for the full-blown approximately 50-60 lines HTML snippet, it just doesn't work. Additionally, all that editing, replacing, patching and stuffing made me think that maybe someone using UIWebViews and JavaScript has a better solution that is known to work.
EDIT AGAIN: I started a bounty, because I cannot believe that there's so few usages of UIWebView that nobody has an answer to this, or already has a big private Tools-class to handle such more complex JavaScript interaction where big chunks of HTML can be included without a reload. :-)
$('.selector').load('/path/to/file',callback);You can load full html files, with extra javascript, in there, and you do not have to worry about any extra serialization. Just write the file as if it was its own document. Your global JS libraries only need to be loaded on your main document, however.loadHTMLString:. The webview will scroll to the top, but i was able to fade it out, load HTML, and then fade it in again with the new content and it looked ok.