'Run injected JavaScript script only once WKWebView web page has fully loaded

I want to run a particular script in WKWebView only once the webpage has fully loaded (including images). What I've been doing so far is running the function func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) and calling self.webView.evaluateJavaScript(...) within didFinish, but I've noticed that didFinish fires before the web page has fully loaded. To run my code correctly, I've been using DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) to delay the function and give the web page enough time to download the content; however, I'd like a more standardized version of this – if the WiFi connection is slow, for example, then the delay isn't enough to prevent the function from firing.

How can I wait to fire my webView.evaluateJavaScript(...) until the web page has fully loaded?

This is what I've attempted so far, but it's not working at all:

self.webView.evaluateJavaScript("function getHTML() { return document.documentElement.innerHTML; } window.onload = getHTML", completionHandler: { (html: Any?, error: Error?) in`

Any help is greatly appreciated!



Solution 1:[1]

I would suggest to create a WkUserScript first with your script -

let script = WKUserScript(
        source: yourScript,
        injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
        forMainFrameOnly: true
    )

then add that to WKUserContentController =

let controller = WKUserContentController()
controller.addUserScript(script)

after that create WKWebViewConfiguration -

let config = WKWebViewConfiguration()
config.userContentController = controller

and finally add that to your webView during initialization -

let webView = WKWebView(frame: webViewOutletThatYouCreated.bounds, configuration: config)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mefahimrahman