user1082920
user1082920

Reputation: 41

Appending HTML to UIWebView

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:

  1. Is it even possible to get the html from a UIWebView?

  2. If so, why does the first line fail/what is the correct method?

  3. Is there a better way to append HTML to a UIWebView?

Thanks for any help.

Upvotes: 4

Views: 2280

Answers (1)

Krease
Krease

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

Related Questions