[英]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).我只想在网页完全加载后(包括图像)在 WKWebView 中运行特定脚本。 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.到目前为止我一直在做的是运行 function
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
并在didFinish
中调用self.webView.evaluateJavaScript(...)
,但我注意到didFinish
之前触发web 页面已完全加载。 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;为了正确运行我的代码,我一直在使用
DispatchQueue.main.asyncAfter(deadline: .now() + 0.6)
来延迟 function 并给 web 页面足够的时间来下载内容; 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.然而,我想要一个更标准化的版本——例如,如果 WiFi 连接速度很慢,那么延迟不足以阻止 function 触发。
How can I wait to fire my webView.evaluateJavaScript(...)
until the web page has fully loaded?我怎么能等到
webView.evaluateJavaScript(...)
直到 web 页面完全加载?
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 -我建议先用你的脚本创建一个 WkUserScript -
let script = WKUserScript(
source: yourScript,
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: true
)
then add that to WKUserContentController =然后将其添加到 WKUserContentController =
let controller = WKUserContentController()
controller.addUserScript(script)
after that create WKWebViewConfiguration -之后创建 WKWebViewConfiguration -
let config = WKWebViewConfiguration()
config.userContentController = controller
and finally add that to your webView during initialization -最后在初始化期间将其添加到您的 webView -
let webView = WKWebView(frame: webViewOutletThatYouCreated.bounds, configuration: config)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.