Deciple
Deciple

Reputation: 1952

How do I edit the HTML in a UIWebView?

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"

Upvotes: 3

Views: 5440

Answers (3)

Gillsoft AB
Gillsoft AB

Reputation: 4225

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

Upvotes: 6

Kevin
Kevin

Reputation: 1157

Try this:

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

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

Upvotes: 1

Paul
Paul

Reputation: 156

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

Upvotes: 1

Related Questions