Set useragent in WKWebview

前端 未结 6 1964
野趣味
野趣味 2021-01-31 14:25

How do I set a custom useragent string in a WKWebView? I\'m trying to embed the version of my app so that my server-side can see what features are available. I found the followi

6条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 15:03

    Custom User Agent

    To set a custom User Agent you can use customUserAgent property:

    let webConfiguration = WKWebViewConfiguration()
    let webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.customUserAgent = "ExampleApp/1.0 (iPhone)"
    

    Available: iOS 9+

    Append to the default User Agent

    To append a custom string at the and of the default user agent you can use applicationNameForUserAgent property:

    let webConfiguration = WKWebViewConfiguration()
    webConfiguration.applicationNameForUserAgent = "ExampleApp/1.0 (iPhone)"
    let webView = WKWebView(frame: .zero, configuration: webConfiguration)
    

    Then it will look for example like:

    Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7
    (KHTML, like Gecko) ExampleApp/1.0 (iPhone)
                        ^^^^^^^^^^^^^^^^^^^^^^^
    

    Available: iOS 9+

提交回复
热议问题