Aaron
Aaron

Reputation: 353

How to run function before WKWebView finishes loading?

I'm creating a Swift iOS project that has multiple WKWebViews that display external websites. Some of these websites I don't have administrative access to, so I use some code to hide a div class. This works fine, but the element is hidden AFTER the page loads, so for a few seconds the div element is shown to the user. See below:

 func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    print("finished")
    let elementID = "some_element"
    let removeElementIdScript = "var element = document.getElementById('\(elementID)'); element.parentElement.removeChild(element);"
    webView.evaluateJavaScript(removeElementIdScript) { (response, error) in
        debugPrint("removed")
    }
}

Is there a way to implement this code before the view loads? Or, if that's not possible, how can I place a mask or hide the view until it loads. I want to avoid showing the div element at all costs.

I've already tried putting the code into the didStartProvisionalNavigation function, but I assume because it runs before the view has loaded, the element isn't present in the view for it to be removed.

Upvotes: 0

Views: 408

Answers (1)

Rob Napier
Rob Napier

Reputation: 299345

Look at WKUserScript, configured as part of the WKUserContentController (defined in the WKWebViewConfiguration). That will probably be good enough, but you can push it further by implementing a content blocker. See WKContentRuleStore for setting those up internally to your app, and specifically Safari Content-Blocking Rules Reference for details on the syntax.

Upvotes: 3

Related Questions