How to get hash fragment of URL from UIWebView

2019-02-19 11:53发布

问题:

I'm trying to get hash fragment of URL loaded in UIWebView, I have tried different approaches it does not seem to work.

For example if the UIWebView is loaded with "http://www.mysite.com/home#main":

NSURL *url = [NSURL URLWithString:@"http://www.mysite.com/home#main"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];

then I want to get the full url, but it only return "http://www.mysite.com/home" with 3 different approaches:

1:

NSString *currentURL = [webView.request.URL absoluteString];

2:

NSString *currentURL = [NSString stringWithFormat:@"%@",[[webView request] URL]];

3:

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

what am I missing

回答1:

Try NSString *fragment = [webView.request.URL fragment];



回答2:

[webview stringByEvaluatingJavaScriptFromString:@"window.location.hash"] is the only way I had success to get the hash fragment in my case

I failed on approaches 1 and approaches 2

maybe your code wrong on someway else......



回答3:

Use the following code snippet
NSLog(@"Hash fragment :%@",[NSString stringWithFormat:@"%@",webview.request.URL.fragment]);



回答4:

I think you should check that, request.url.absolutestring has fragment on shouldStartLoadWithRequest, webViewDidFinishLoad.