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!
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.