WKWebview: Disable interaction and clicks on links

The WKNavigationDelegate solution only prevents the user from following links. I also have form controls that I want to prevent interaction with, while still allowing the page to be scrolled. Eventually I figured out that this could be achieved by disabling the subviews of the web view's scroll view:

Swift

self.webView.scrollView.subviews.forEach { $0.isUserInteractionEnabled = false }

Objective-C

for (UIView *subview in self.webView.scrollView.subviews)
{
    subview.userInteractionEnabled = NO;
}

These javascript lines will disable long presses and link touches by overriding the HTML. Frame based things like embedded youtube videos will still work.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    webView.evaluateJavaScript("document.documentElement.style.webkitUserSelect='none'")
    webView.evaluateJavaScript("document.documentElement.style.webkitTouchCallout='none'")
    webView.evaluateJavaScript("var elems = document.getElementsByTagName('a'); for (var i = 0; i < elems.length; i++) { elems[i]['href'] = 'javascript:(void)'; }")
}

First, you have to give the delegate to your webkit then add below code. Swift 5.0

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    Activity.stopAnimating()
    let javascriptStyle = "var css = '*{-webkit-touch-callout:none;-webkit-user-select:none}'; var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; style.appendChild(document.createTextNode(css)); head.appendChild(style);"
    webView.evaluateJavaScript(javascriptStyle, completionHandler: nil)
}

What this code will do, we add programmatically css that will disable interaction in webview


Implement the WKNavigationDelegate protocol:

@interface ViewController () <WKNavigationDelegate>

Set your WKWebView's navigationDelegate property:

self.wkWebView.navigationDelegate = self;

Then implement the policy for the URL(s) that you want to restrict:

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {

    if ([navigationAction.request.URL.absoluteString containsString:@"somedomain.com/url/here"]) {
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    else {
        decisionHandler(WKNavigationActionPolicyCancel);
    }
}