Take the 2-minute tour ×

Here's my Code:

NSString *js =[NSString stringWithFormat:@"document.getElementsByTagName('body')[0].innerHTML = '<h1>%@</h1>';",s];
[pageView stringByEvaluatingJavaScriptFromString:js];

pageView is a UIWebView already loaded with an html document. I want it to show the NSString s. However, when this function is called, the visible html stays the same. I know s has a value because it is printing properly to the console one line above this. If I replace "%@" with say, "poot", "poot" appears in the h1 tag of the html as it should.

Shouldn't I be able to send s to the html like this?


share|improve this question
add comment

1 Answer

What is the expected content of s? If it makes your JavaScript syntactically invalid, that could cause this problem.

share|improve this answer
Interesting. If I change s to a short, single-word NSString before this is called, it does work. I am not sure why what was there would invalidate it though. The existing value of s is text data pulled from a p tag in a different html document. It's a bit of a longer string, being a whole paragraph, but that shouldn't invalidate the js. –  Chris Nov 11 '10 at 15:55
Unless it contains newlines, or single quote characters. Don't forget, the resultant JavaScript string must be a fully valid program fragment. –  Adam Wright Nov 11 '10 at 15:58
S does contain single quotes, used as apostrophes in the paragraph. It also uses "&#8212;" for "-" characters. I figured if I passed it this way it would just go through as a string literal. –  Chris Nov 11 '10 at 16:12
So your JavaScript ends up reading as document.getElementsByTagName('body')[0].innerHTML = '<h1>I'm testing</h1>', which is parsed as document.getElementsByTagName('body')[0].innerHTML = '<h1>I' then ` m testing/h1>'`, which is syntactically invalid. You'll need to escape the quotes, or use double quoting. –  Adam Wright Nov 11 '10 at 16:20
Thanks, will try this out. Will the special character codes give me any trouble? –  Chris Nov 12 '10 at 18:06
show 1 more comment

Your Answer


