【问题标题】:How do I edit the HTML in a UIWebView?如何在 UIWebView 中编辑 HTML?
【发布时间】:2023-03-12 19:22:02
【问题描述】:

我有一个加载 HTML 的 UIWebView。如何访问这些 HTML 元素并更改它们?

我想做类似的事情:webView.getHTMLElement(id: main-title).value = "New title"

【问题讨论】:

标签: ios swift uiwebview swift2


【解决方案1】:

如果你想在表单中编辑它,你可以这样做:

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

或者如果不是表格,也许是这个(未经测试):

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

注意!我假设它是您想要更改的可编辑字段。否则,您正在谈论解析,并且该概念的工作方式如下:

    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]];
        }
    }

您可以在此处阅读有关解析的更多信息:Objective-C html parser

【讨论】:

    【解决方案2】:

    先看这个帖子 --> Getting the HTML source code of a loaded UIWebView

    然后看看这个 --> Xcode UIWebView local HTML

    希望这对你有用

    【讨论】:

      【解决方案3】:

      试试这个:

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

      确保在加载文档后执行此代码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-29
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        相关资源
        最近更新 更多