Search code examples
htmliosswiftuiwebview

Edit html code from UIWebView swift


I am presenting a WebView in my app, however, there are some modifications I would like to make on the website I am presenting. If I load google.com, for example, I might want to change the text of the "google search" button. How do I go about doing this?

The similar questions asked are all in Objective C and do not seem to be working. Thank you in advance.


Solution

  • I think this will help for you. In 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!)")
        }
    
    }