从UIWebView swift编辑html代码

时间:2017-08-16 11:18:53

标签: html ios swift uiwebview

我在我的应用程序中展示了一个WebView,但是,我想在我提交的网站上进行一些修改。例如,如果我加载google.com,我可能想要更改" google搜索"按钮。我该怎么做呢?

提出的类似问题都在目标C中,似乎没有起作用。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

我认为这会对你有所帮助。在Swift3中

@IBOutlet weak var webView: UIWebView!
var firstLoad = true
override func viewDidLoad() {
    super.viewDidLoad()
    self.webView.delegate = self
    self.webView.loadRequest(URLRequest(url: URL(string: "https://www.google.com.pk/")!))
    // Do any additional setup after loading the view, typically from a nib.
}

func webViewDidFinishLoad(_ webView: UIWebView) {
    let evaluate: String = "document.getElementById('main-title').value='\("New title")';"
    webView.stringByEvaluatingJavaScript(from: evaluate)

    //or
    if firstLoad {
        firstLoad = false
        let html: String? = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")
        //Edit html here, by parsing or similar.
        webView.loadHTMLString(html!, baseURL: Bundle.main.resourceURL)

        //print HTML for testing
        print("HTML \(html!)")
    }

}