Search code examples
swiftswiftuisafariwebkitwhatsapp

WKWebView not loading WhatsApp Web


I have a macOS web browser made using SwiftUI and WebKitView that works well with most sites but some pages such as WhatsApp i get the following error message to upgrade to a newer version of safari.

enter image description here

WebView

struct WebView: NSViewRepresentable {
    @ObservedObject var webModel: WebStateModel
    
    let wkWebview = WKWebView()
    
    func makeNSView(context: Context) -> WKWebView {
        if let theUrl = webModel.url {
            let request = URLRequest(url: theUrl, cachePolicy: .returnCacheDataElseLoad)
            wkWebview.load(request)
        }
        
        let preferences = WKPreferences()
        preferences.javaScriptEnabled = true
        
        return wkWebview
    }
    
    func updateNSView(_ nsView: WKWebView, context: Context) {
        if let theUrl = webModel.url {
            let request = URLRequest(url: theUrl, cachePolicy: .returnCacheDataElseLoad)
            nsView.load(request)
        }
    }

Solution

  • First of all you can use Safari Services instead of WKWebView, so you will be actually using a compatible browser.

    Otherwise, it depends how the site checks the browser it's loaded in.

    • The most primitive way to check the browser type and version, is to look at browser's user agent string. For cases like this, you may be able to surpass the check by setting a customUserAgent on WKWebView to whatever the site supports. It's a hack though, as your WKWebView pretends to be a different browser.

    • More sophisticated cases check not the actual browser, but the capabilities they need. For example the site may check if cookies, or local storage is enabled. In this case you should just enable the required capabilities on your WKWebView.

    • In third case, site tries to explicitly block embedding its content into WKWebView or WebView. In that case you have to respect the site owner wishes, and not try to embed the site.

    Which one is the case of WhatsApp, not quite sure. You will have to experiment I guess.