21

I'm creating an app which has a text field & go button on top and web view below them. When user enters URL in text field and clicks "Go" button, it will start loading the page in webview. When user clicks on some link, i want to show the URL of the page (being loaded) in the text field. How can I get that URL of the link clicked.

Also some websites are there which will redirect to some other site. So my question is how to show the URL of the page being loaded in the text field?

Satyam
  • 15,493
  • 31
  • 131
  • 244

3 Answers3

44

Implement this in your UIWebViewDelegate class

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    //CAPTURE USER LINK-CLICK.
      NSURL *url = [request URL];
      yourTextBox.text =   [url absoluteString];


      return YES;   
}
Mihir Mehta
  • 13,743
  • 3
  • 64
  • 88
  • 2
    This doesnot work when i load youtube in webview... Anything i miss. Please help. – Warrior Sep 15 '12 at 03:05
  • @Warrior did you find something for it? I search for it; http://stackoverflow.com/questions/18692540/get-clicked-linked-on-uiwebview-navigating-on-m-youtube-com-on-ios – Bilgin Kılıç Sep 09 '13 at 06:31
12

If you specifically want the url of links clicked by user then find it in this way.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (navigationType == UIWebViewNavigationTypeLinkClicked) {
        NSLog(@"link clicked = %@",request.mainDocumentURL);
    }
    return YES;
}

Also if you want the url of any request, requested from client side either by taping on a link or specifically requested from webView by you, use

NSLog(@"link clicked = %@",self.webView.request.mainDocumentURL);

and if you want the any current url requested from client side either by you or they are requested by the page you opened automatically, use.

NSLog(@"link clicked = %@",self.webView.request.URL);

This is all that I have found after a long search, may be it will help someone.

iHulk
  • 4,869
  • 2
  • 30
  • 39
4

There's a delegate method for that purpose, implement it like this:

- (void)webViewDidStartLoad:(UIWebView *)webView {
    NSURL* url = [webView.request URL];
    urlTextField.text = [url absoluteString];
}
Felix
  • 35,354
  • 13
  • 96
  • 143
  • This is working fine. But a problem noticed. That is I entered http://www.yahoo.com and its loading fine. but textfield is being cleared. when i click some links in yahoo page, then onwards its showing the URL properly. – Satyam Jan 13 '11 at 13:31