WebView:How to detect if I am on the original web

2019-08-30 11:11发布

I have this method that goes back to previous webpage in a web view under certain circumstance and it works fine. However, I want to implement a function that checks if I am on the original web page and if so, when I push the back button it takes me to a navigation view controller. The original page is this code [webView loadHTMLString:self.item.description baseURL:[NSURL URLWithString:self.item.link]];. Now I need to figure out how to check if I am on that page and if so I need to execute this code: [self.navigationController popViewControllerAnimated:YES];. Any help will be appreciated.

- (void)back
{
    if ([webView canGoBack]) {
        [webView goBack];
    } else {
        [webView loadHTMLString:self.item.description baseURL:[NSURL URLWithString:self.item.link]];    
    }
}

2条回答
Animai°情兽
2楼-- · 2019-08-30 11:26

You can use the delegate method shouldStartLoadWithRequest of UIWebViewDelegate to check what contains in the url. if you find it then just go NavigationController

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    if ([[request.URL absoluteString] rangeOfString:@"http://yourURL"].location!=NSNotFound) {
       [self.navigationController popViewControllerAnimated:YES];.    
    }
}
查看更多
太酷不给撩
3楼-- · 2019-08-30 11:32

You need to add

       <UIWebViewDelegate> 

to the header. Then set webView.delegate to yes;

Once you have it set as a delegate, then you can get the absoluteString and the requestURL, and override the method. With the absoluteString you can check for a substring, text, domain, basically anything you want! You override shouldStartLoadWithRequest or webViewDidFinishLoad:

   -(void)webViewDidFinishLoad:(UIWebView *)webView 
   -(void)shouldStartLoadWithRequest :(UIWebView *)webView 

That calls everytime any webpage is loaded.

查看更多
登录 后发表回答