WKWebView function for detecting if the URL has changed

前端 未结 3 951
孤城傲影
孤城傲影 2020-12-03 11:19

Is there a function for the WKWebView class that allows you to detect whenever the URL of that WebView has changed?

The didCommit and didStartProv

3条回答
  •  情歌与酒
    2020-12-03 11:54

    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.

    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
    }
    

    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
    }
    

    All you'd have to do is implement these delegate methods (in Swift) and do what you want when you see it change.

提交回复
热议问题