I need a solution to ensure that a specific script in WKWebView only runs once the webpage is fully loaded, including images. Currently, I've tried executing the function
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
and calling self.webView.evaluateJavaScript(...)
within didFinish
. However, I have observed that didFinish
activates before the webpage finishes loading. In order to run my code accurately, I have resorted to using DispatchQueue.main.asyncAfter(deadline: .now() + 0.6)
to delay the function execution, allowing sufficient time for the content to download. Nevertheless, I am seeking a more reliable approach as this method may not be suitable if there are slow WiFi connections causing the function to trigger prematurely.
Is there a way to delay the execution of webView.evaluateJavaScript(...)
until the entire webpage has finished loading?
The following snippet represents my failed attempts:
self.webView.evaluateJavaScript("function getHTML() { return document.documentElement.innerHTML; } window.onload = getHTML", completionHandler: { (html: Any?, error: Error?) in`
Any assistance provided will be greatly appreciated!