Mobile site detection should not rely on Safari in user agent

Hi all,

Thanks for the fantastic piece of software that Discourse is, it’s incredible!

We are using Discourse for the community of our app Agenda, our users love it. This is in part because we built it straight in the app using a WKWebView on mac and iOS. Unfortunately this gives a problem on iPhones as apparently discourse fails to detect it’s running on mobile.

Compare the following screenshots taken from Mobile Safari (left) and Agenda (right) on the same device:

The issue seems to be caused by Discourse parsing the User Agent string (left mobile safari, right Agenda using a stock WKWebView) for the word Safari or the word Mobile:

If I indeed tell the WKWebView to set the custom user agent to the same string as mobile Safari it works correctly. Unfortunately this is not a really great solution as it would force us to spoof an incorrect user agent of an incorrect safari version etc. I hope this can be fixed (for example by also checking for the word iPhone)…

Thanks and keep up the great work!
Alex

1 Like

Unlikely, we have run into many complex issues with string based user agent detection in the past. If you want to 100% be seen as a mobile browser you need the word “mobile” in there from our perspective.

2 Likes

Nasty. FWIW if anyone hits the same issue, here’s the workaround I added, which I guess has to stay then:

    // we need to force a user agent that is recognized by Discourse as mobile
    webView.evaluateJavaScript("navigator.userAgent") { [weak self] result, error in
        if let userAgent = result as? String, error == nil {
            self?.webView.customUserAgent = userAgent + " Mobile"
        }
    }
5 Likes