Adding HTML to UIWebView

I am trying to add some HTML to a UIWebView . It does not work and instead overwrites the existing HTML, as oldHTML below is always empty. HTML line starts with

 <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 possible to get html with UIWebView ?

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

  • Is there a better way to add HTML to a UIWebView ?

Thanks for any help.

+4
source share
1 answer

I suspect you are trying to get the old html, your page has not finished loading yet, so it returns an empty string.

Try creating and assigning a UIWebViewDelegate to your view, which implements webViewDidFinishLoad: and puts your code above in this function - oldHTML should be non-empty at that point.

As for the best way, you can add content through javascript 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 would recommend clearing it a bit, as it is not fully protected, but it needs to understand how to use javascript to introduce new elements to the page.

+2
source

Source: https://habr.com/ru/post/1384842/


All Articles