Disable links in UIWebView?

0 votes
asked Jan 20, 2010 by don-wilson

I am loading some content from the web into a UIWebView, but I'd like all links to be disabled in the UIWebView. Is this possible? I could parse the text, but I'm looking for something easier.

5 Answers

0 votes
answered Jan 20, 2010 by dave-delong

You can give the UIWebView a delegate and implement the -webView:shouldStartLoadWithRequest:navigationType: delegate method to return NO; (except on the initial load).

That will prevent the user from viewing anything but that single page.

To provide an example requested in the comments... Start with allowLoad=YES and then:

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

- (void)webViewDidFinishLoad:(UIWebView*)webView {
    allowLoad = NO;
}
0 votes
answered Jan 25, 2014 by jeffrey-neo

You can disable data detect from your webview.

[webView setDataDetectorTypes:UIDataDetectorTypeNone];
0 votes
answered Jan 20, 2016 by felipe-jun

I had a similar need and for some cases just using the webViewDidFinishLoad was not enough, so I used the webViewDidStartLoad to cover all cases:

func webViewDidStartLoad(webView: UIWebView) {
    startedLoading = true
}

func webViewDidFinishLoad(webView: UIWebView) {
    alreadyOpen = true
}

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
    if startedLoading && alreadyOpen {
        // do something
        return false
    }else if startedLoading && !alreadyOpen{
        return false
    }else if !startedLoading {
        return true
    }
    return true
}

In some cases when the html was loaded but some resources, like images and some heavy assets inside the DOM were not the didFinishLoad method was not fired and the user could navigate in this "short" interval.

0 votes
answered Jan 28, 2016 by serenn

Tested in Swift 2.2: This approach doesn't involve having an extra variable to test if this is the initial load or not. Simply check the type of request (in this case, LinkClicked) and return false in that case. Otherwise simply return true!

(Of course make sure you set the webView.delegate)

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if navigationType == .LinkClicked {
            return false
        }

        return true
    }
0 votes
answered Sep 15, 2017 by jeremiah-widjaja

For swift 3:

Try removing the types you don't want to show as link from webView.dataDetectorTypes

webView.dataDetectorTypes.remove(UIDataDetectorTypes.all)
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...