How to use shouldStartLoadWithRequest method of UIWebView Delegate

lakesh picture lakesh · Mar 4, 2013 · Viewed 18.6k times · Source

I need to remove the hyperlinks from the URL shown in UIWebView and I have looked at this question: Removing hyper links from a URL shown in UIWebView.

I know I need to use this method:

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

But I still seem to have some problems.

Firstly, how do i avoid only certain links (for example: www.google.com).

Next, how do i avoid all links in my UIWebView?

My code looks like this:

[webUI loadHTMLString:[strDescription stringByDecodingHTMLEntities] baseURL:nil];
webUI.dataDetectorTypes = UIDataDetectorTypeNone;

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish loading");

    [webUI stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\".active\", \"pointer-events: none;\");document.styleSheets[0].addRule(\".active\", \"cursor: default;\")"];

}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
       return YES;
}

Need some guidance. Thanks..

The HTML string looks like this:

> <div style="font-family: Helvetica"><div style="color: #FFFFFF;"><div
> style="font-family: Helvetica;"><p><span style="font-size:
> 24px;"><strong>Optimal Performance Always</strong></span><span
> style="font-size: 18px;"><br /></span></p><p><span style="font-size:
> 18px;">The standard servicing package<a
> href="http://www.google.com">www.google.com</a></div>

Answer

Marcelo Fabri picture Marcelo Fabri · Mar 4, 2013

If you want to disable all links after the first page was loaded you can add a property to store if the page was loaded and use its value on webView:shouldStartLoadWithRequest:

@property(nonatomic) BOOL pageLoaded; // initially NO

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"finish loading");

    [webUI stringByEvaluatingJavaScriptFromString:@"document.styleSheets[0].addRule(\".active\", \"pointer-events: none;\");document.styleSheets[0].addRule(\".active\", \"cursor: default;\")"];

    // after all your stuff
    self.pageLoaded = YES;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
   return ! self.pageLoaded;
}

Note that this doesn't hide links, it only makes the webview not load them.

Also, you can check request.URL on webView:shouldStartLoadWithRequest:navigationType: to only load certain pages. Another way would be check navigationType value:

enum {
   UIWebViewNavigationTypeLinkClicked,
   UIWebViewNavigationTypeFormSubmitted,
   UIWebViewNavigationTypeBackForward,
   UIWebViewNavigationTypeReload,
   UIWebViewNavigationTypeFormResubmitted,
   UIWebViewNavigationTypeOther
};