itgiawa
itgiawa

Reputation: 1616

Inject HTML to the end of webpage on iPhone using javascript

I have a UIWebView and I want to inject some HTML to the end of it after its been loaded.

NSString* javaScript = [NSString stringWithFormat:@"document.body.innerHTML += '%@'", arbitraryHTML];
[self.webView stringByEvaluatingJavaScriptFromString:javaScript];

The above code works, but only if arbitraryHTML is properly formated. E.g. the single quote ' is escaped as \' I'd like to clean up HTML in genearl so that I can pass it to a javascript function.

What are other characters that I need to escape or strings that could cause problems?

Here's an example of some HTML that breaks the above code:

<span><a onmouseover=\\\"jQuery\\'# >Test</a></span>"

Can this be done in genearl? What else am I missing?

Thanks!

Upvotes: 1

Views: 293

Answers (2)

user123444555621
user123444555621

Reputation: 153006

You need to make sure the JS engine does not throw up. So you need to escape single quotes and backslashes. This should do the trick:

arbitraryHTML = [[arbitraryHTML
        stringByReplacingOccurrencesOfString:@"\\" withString:@"\\\\"]
        stringByReplacingOccurrencesOfString:@"'" withString:@"\\'"]];

Note that you also need to escape backslashes inside Objective-C strings as seen above.

Upvotes: 2

itgiawa
itgiawa

Reputation: 1616

Turns out that its not enough to escape just the single quote character. I also needed to escape /n and /r to make this work with all HTML in general.

There may be some other character that I missed, if I find a case I'll post it.

Upvotes: 1

Related Questions