3

I have a UIWebView that loads HTML. How do I access those HTML elements and change them?

I want to do something like: webView.getHTMLElement(id: main-title).value = "New title"

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Deciple
  • 1,864
  • 3
  • 16
  • 19

3 Answers3

6

If you want to edit it in a form, this is how you can do it:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   NSString *evaluate = [NSString stringWithFormat:@"document.form1.main-title.value='%@';", @"New title"];
   [webView stringByEvaluatingJavaScriptFromString:evaluate];
}

Or if not in a form, maybe this (untested):

- (void)webViewDidFinishLoad:(UIWebView *)webView {
   NSString *evaluate = [NSString stringWithFormat:@"document.getElementById('main-title').value='%@';", @"New title"];
   [webView stringByEvaluatingJavaScriptFromString:evaluate];
}

Note! I assume it is an editable field that you want to change. Otherwise you are talking about parsing and that concept works like this:

    static BOOL firstLoad = YES;

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        if (firstLoad) {
            firstLoad = NO;
            NSString *html = [_webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.outerHTML"];
            //Edit html here, by parsing or similar.
            [webView loadHTMLString:html baseURL:[[NSBundle mainBundle] resourceURL]];
        }
    }

You can read more about parsing here: Objective-C html parser

Gillsoft AB
  • 4,185
  • 2
  • 19
  • 35
1

First look at this post --> Getting the HTML source code of a loaded UIWebView

Then check this one out --> Xcode UIWebView local HTML

Hopefully this works out for you

Community
  • 1
  • 1
Paul
  • 156
  • 9
1

Try this:

[webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"main-title\").value = \"New Title\""];

make sure you execute this code after the document is loaded.

Kevin
  • 1,147
  • 11
  • 21