Detect scroll in Webview with Swift

I am using SwiftUI, so I have a wrapper around the Webview, like this:

import SwiftUI
import WebKit


struct WebView: UIViewRepresentable {
    var url: String
    let webView = WKWebView()
    
    func makeUIView(context: Context) -> WKWebView  {
        webView.evaluateJavaScript("navigator.userAgent") { (result, error) in
            print(result as! String)
        }
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        let request = URLRequest(url: URL(string:url)!)
        uiView.load(request)
    }
}

How can I execute a function/method whenever the user makes scroll to the website?


To get scroll position updates you need to create coordinator and override makeCoordinator() method and return instance of your coordinator. In makeUIView(_:) method just assign scrollview delegate to context.coordinator (context object in provided in arguments of makeUIView method)

Pass binding from view to coordinator and coordinator is responsible to update that binding. Here is code for that

struct WebView: UIViewRepresentable {
    
    var url: String
    @Binding var contentOffset: CGPoint
    
    init(url: String, contentOffset: Binding<CGPoint>) {
        self.url = url
        _contentOffset = contentOffset
    }
    
    let webView = WKWebView()
    
    func makeUIView(context: Context) -> WKWebView  {
        webView.scrollView.delegate = context.coordinator // assign delegation
        
        webView.evaluateJavaScript("navigator.userAgent") { (result, error) in
            print(result as! String)
        }
        return webView
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        let request = URLRequest(url: URL(string:url)!)
        uiView.load(request)
    }
    
    func makeCoordinator() -> Coordinator {
        .init(contentOffset: $contentOffset) // create coordinator for delegation
    }
    
    
    class Coordinator: NSObject, UIScrollViewDelegate {
        
        @Binding var contentOffset: CGPoint
        
        init(contentOffset: Binding<CGPoint>) {
            _contentOffset = contentOffset
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            contentOffset = scrollView.contentOffset
        }
    }
}