Get current URL of UIWebView

后端 未结 14 1941
天命终不由人
天命终不由人 2020-11-29 16:08

I already tried getting the current URL of my UIWebView with: webview.request.URL. Unfortunately the NSURL was empty. Anything wrong h

相关标签:
14条回答
  • 2020-11-29 16:30

    Tried this for google search results on iPhone:

     NSString* currentURL = webView.request.URL.absoluteString;
     NSString* mainDocumentURL = webView.request.mainDocumentURL.absoluteString;
    

    Both return the same string!

    0 讨论(0)
  • 2020-11-29 16:36

    This is not correct, and will return a nil:

    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location"];
    

    However, the code below can get a URL, but the url may not be the current URL:

    NSString *url = _webView.request.URL.absoluteString;
    

    The correct one is:

    NSString *currentURL = [_webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
    
    0 讨论(0)
  • 2020-11-29 16:37

    Matt's version is much cleaner. I recommend everyone to use that one instead of this

    You could try this:

    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location"];
    
    0 讨论(0)
  • 2020-11-29 16:37

    implement delegate method,

    - (BOOL)webView:(UIWebView *)webview shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {
        NSString  *URL = request.URL.absoluteString;    NSLog(@"%@",URL);
    }
    

    URL is the what you exactly needed.

    0 讨论(0)
  • 2020-11-29 16:41

    This always works . .

    NSString* url= [webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
    
    0 讨论(0)
  • 2020-11-29 16:42

    I too found that the approved answer above was not reliable. But with a slight modification, it seems to work every time:

    NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];
    

    Note the addition of ".href" to the Javascript as this is hidden at the end of the line of code.

    0 讨论(0)
提交回复
热议问题