Reputation: 41
I'm trying to append some HTML to a UIWebView
. It doesn't work and instead overwrites the existing HTML, since oldHTML
below is always empty. The HTML string starts off as
<html><font color="0x0000FF">Blue text</font></html>
Code:
NSString *oldHTML = [myWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];
NSString *html = [NSString stringWithFormat:@"%@%@%@%@", @"<html>", oldHTML, htmlToAdd, @"</html>"];
[myWebView loadHTMLString:html baseURL:nil];
So my questions are:
Is it even possible to get the html from a UIWebView
?
If so, why does the first line fail/what is the correct method?
Is there a better way to append HTML to a UIWebView
?
Thanks for any help.
Upvotes: 4
Views: 2280
Reputation: 16215
I suspect at the point you're trying to get the old html, your page hasn't completed loading yet, which is why it's returning a blank string.
Try creating and assigning a UIWebViewDelegate
for your view that implements webViewDidFinishLoad:
and putting your code above in that function - oldHTML should be non-blank at that point.
As for a better way, you can inject the content via javascript with something like this:
NSString *injectSrc = @"var i = document.createElement('div'); i.innerHTML = '%@';document.documentElement.appendChild(i);";
NSString *runToInject = [NSString stringWithFormat:injectSrc, @"Hello World"];
[myWebView stringByEvaluatingJavascriptFromString:runToInject];
I'd recommend cleaning this up a bit, as it's not totally secure, but it should get the idea across of using javascript to inject new elements onto the page.
Upvotes: 2