WKWebView函数用于检测URL是否已更改 [英] WKWebView function for detecting if the URL has changed
问题描述
是否有WKWebView类的函数允许您检测WebView的URL何时发生更改?
Is there a function for the WKWebView class that allows you to detect whenever the URL of that WebView has changed?
didCommit 使用WebView中的某些元素时,code>和
didStartProvisionalNavigation
函数似乎并不总是闪现。
The didCommit
and didStartProvisionalNavigation
functions don't always seem to fire when working with certain elements within the WebView.
编辑:尝试添加通知观察者。以下是我到目前为止:
Attempted adding a Notification observer. Here's what I have thus far:
extension Notification.Name {
static let checkURL = Notification.Name("checkURL")
}
NotificationCenter.default.post(name: .checkURL, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(getter: webView.url), name: .checkURL, object: webView.url)
推荐答案
你是什么意思他们似乎并不总是开火?什么样的元素?他们必须让WkWebView工作。
What do you mean they don't always seem to fire? What kind of elements? They have to in order for the WkWebView to work.
您尝试更改URL的第一个迹象是:decisionPolicyForNavigationAction
Your first indication that the URL is trying to change is in: decidePolicyForNavigationAction
- (void) webView: (WKWebView *) webView decidePolicyForNavigationAction: (WKNavigationAction *) navigationAction decisionHandler: (void (^)(WKNavigationActionPolicy)) decisionHandler {
NSLog(@"%s", __PRETTY_FUNCTION__);
decisionHandler(WKNavigationActionPolicyAllow); //Always allow
NSURL *u1 = webView.URL;
NSURL *u2 = navigationAction.request.URL; //If changing URLs this one will be different
}
当您到达时:didStartProvisionalNavigation它已经改变了。
By the time you get to: didStartProvisionalNavigation It has changed.
- (void) webView: (WKWebView *) webView didStartProvisionalNavigation: (WKNavigation *) navigation {
NSLog(@"%s", __PRETTY_FUNCTION__);
NSURL *u1 = webView.URL; //By this time it's changed
}
你所要做的就是实现这些委托方法(在Swift中)并在你看到它改变时做你想做的事。
All you'd have to do is implement these delegate methods (in Swift) and do what you want when you see it change.
这篇关于WKWebView函数用于检测URL是否已更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!