用于检测 URL 是否已更改的 WKWebView 函数

WKWebView function for detecting if the URL has changed

WKWebView class 是否有一个函数允许您检测该 WebView 的 URL 何时发生变化?

在 WebView 中处理某些元素时,didCommitdidStartProvisionalNavigation 函数似乎并不总是触发。

编辑: 尝试添加通知观察器。这是我到目前为止所拥有的:

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)

您可以添加观察员:

[webView_ addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:NULL];

以及 URL 更改时调用的相应方法:

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context

你说他们似乎并不总是开火是什么意思?什么样的元素?他们必须这样做才能使 WkWebView 正常工作。

URL 试图更改的第一个指示是: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 它已经改变了。

- (void) webView: (WKWebView *) webView didStartProvisionalNavigation: (WKNavigation *) navigation {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    NSURL *u1 = webView.URL;  //By this time it's changed
}

您所要做的就是实现这些委托方法(在 Swift 中)并在看到它发生变化时执行您想要的操作。

Swift版本

// Add observer
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)

// Observe value
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
    if let key = change?[NSKeyValueChangeKey.newKey] {
        print("observeValue \(key)") // url value
    }
}