Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get URL of all items tapped with WKWebView

I have a WKWebView loading a page in iOS. If the user navigates to another page in the WKWebView, I can get the URL they clicked as follows:

var clickedUrl = String()

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {

    clickedUrl = webView.URL?.absoluteString as String! // GETS URL OF CURRENT PAGE LOADED
}

If the user goes to YouTube, clickedUrl = http://www.youtube.com, which is great. HOWEVER... If the user then clicks on a video - nothing. And another video - nothing. I do not get the URL of the clicked video. The same happens on Vimeo and various other sites.

I have done some research on here and found other posts, and it would seem this has something to do with 'WKWebView does not report finish of loading on non main frames', but no explanation of how to get at the URL that has been loaded. I am guessing that this has something to do with sites like YouTube are using JavaScript to navigate to other pages on their site and load them.

I have also tried webView(_:decidePolicyForNavigationAction:). This function is more verbose, but this function also does not detect the URL of links clicked within sites like YouTube. What I want to do is get the URL of everything the user clicks. I am guessing I need to go deep into NSURL or NSURLRequest to get this, but I cannot work out how to do this. Any help would be greatly appreciated.

Apologies... Please see duplicate/similar question: Detect when WKWebView has finished loading EVERY time

like image 448
AT3D Avatar asked Apr 09 '15 07:04

AT3D


1 Answers

You will need to observe WKWebViews URL KVO property:

Swift:

webView.addObserver(self, forKeyPath: "URL", options: .New, context: nil)

Objective-C:

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

And then access WKWebViews URL property as you normally would inside observeValueForKeyPath:ofObject:change:context.

like image 93
s1ris Avatar answered Nov 17 '22 06:11

s1ris