Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cocoa WebKit/WebView delegate for location change? (User clicked link, javascript action, etc)

I have added a WebView to a Cocoa application and I'm trying to figure out which delegate I can use to detect when navigation changes (user clicks a link, or javascript fires to change the location, etc).

The WebView class reference contains four delegates (WebFrameLoadDelegate Protocol Reference, WebPolicyDelegate Protocol Reference, WebResourceLoadDelegate Protocol Reference and WebUIDelegate Protocol Reference) and I have looked at each of these, but I cannot seem to find how to detect this. Am I missing something blatantly obvious or is there no way to get this?

tldr - Trying to figure out how I can set a delegate to get an event when the WebView is changing URL. (Specifically I need to know what the new URL is).

like image 604
Kyle Avatar asked Oct 15 '11 14:10

Kyle


2 Answers

Using WebKit (i.e. MacOS X) then probably the best place to track requests is in webView:identifierForInitialRequest:fromDataSource:, although webView:resource:willSendRequest:redirectResponse:fromDataSource: is also good, and has the advantage of allowing you to modify the request.

As with iOS, you can use [request URL].

Set this via [webView setResourceLoadDelegate:self];.

The resource load delegate (as above) gives better options to handle the request, in my opinion, than the policy delegate methods.

like image 109
Paul Lynch Avatar answered Nov 03 '22 08:11

Paul Lynch


I recommend you implement these two WebPolicyDelegate methods:

-webView:decidePolicyForNavigationAction:request:frame:decisionListener:
-webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:

That will tell you the new URL being navigated to, but also give you a chance to change the default behaviour. e.g. you may not WebKit attempting to open new windows.

like image 5
Mike Abdullah Avatar answered Nov 03 '22 09:11

Mike Abdullah