Search code examples
iosswiftuiwebkitwkwebview

SwiftUI WKWebView disable link interactions


I am looking for a way to disable a user interacting with links and images in SwiftUI using WKWebView. I have tried various ways but none have worked, and I have seen and tried the following post but nothing worked:

WKWebview allowsLinkPreview to false breaks text selection

WKWebview: Disable interaction and clicks on links

I am displaying a website that I have permission to display but due to its abnormal HTML structure it makes it hard to display the context, so I decided to try disabling user interactions with links. I do still want user interactions enabled so the user can scroll through the calendar presented to them, but not be able to click on links. If you have any suggestion I am open to them.

Here is my code:

struct CalanderWeb : UIViewRepresentable {

    @State var request: URLRequest

    func makeUIView(context: Context) -> WKWebView  {

        return WKWebView()
    }

    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.scrollView.isScrollEnabled = true
        uiView.isOpaque = false
        uiView.allowsBackForwardNavigationGestures = false

        uiView.load(request)
    }

    func makeCoordinator() -> CalanderWeb.Coordinator {
        Coordinator(self)
    }


    class Coordinator: NSObject, WKNavigationDelegate {
        let parent: CalanderWeb

        init(_ parent: CalanderWeb) {
            self.parent = parent
        }

        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        }

        func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {

        }

        func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {

        }

        func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
            decisionHandler(.cancel)
        }
    }

}

Thank You.


Solution

  • Here is correct delegate callback

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            decisionHandler(.cancel)
        } else {
            decisionHandler(.allow)
        }
    }
    

    depending of used HTML, probably also might be disabled .formSubmitted, if needed.