Set useragent in WKWebview

前端 未结 6 1963
野趣味
野趣味 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 14:43

    the default User-Agent in WKWebView is as

    Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X)
    

    You can customize the WKWebView User-Agent

    webView.customUserAgent = "zgpeace User-Agent"
    

    I write a demo for WKWebView:

    func requestWebViewAgent() {
            print("requestWebViewAgent")
    
            let webView = WKWebView()
            webView.evaluateJavaScript("navigator.userAgent") { (userAgent, error) in
                if let ua = userAgent {
                    print("default WebView User-Agent > \(ua)")
                }
    
                // customize User-Agent
                webView.customUserAgent = "zgpeace User-Agent"
            }
        }
    

    Warning: "User-Agent" is nil from webView, when webView is released. You can set webView object as property to keep the webView.

    NSURLSession send User-Agent by default.
    default User-Agent style like.

    "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
    

    We can customize the User-Agent.

    let config = URLSessionConfiguration.default
    config.httpAdditionalHeaders = ["User-Agent": "zgpeace User-Agent"]
    

    I write a demo for URLSession in the below.

         func requestUrlSessionAgent() {
            print("requestUrlSessionAgent")
    
            let config = URLSessionConfiguration.default
            // default User-Agent: "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
            // custom User-Agent
            config.httpAdditionalHeaders = ["User-Agent": "zgpeace User-Agent"]
            let session = URLSession(configuration: config)
    
            let url = URL(string: "https://httpbin.org/anything")!
            var request = URLRequest(url: url)
            request.httpMethod = "GET"
    
            let task = session.dataTask(with: url) { data, response, error in
    
                // ensure there is no error for this HTTP response
                guard error == nil else {
                    print ("error: \(error!)")
                    return
                }
    
                // ensure there is data returned from this HTTP response
                guard let content = data else {
                    print("No data")
                    return
                }
    
                // serialise the data / NSData object into Dictionary [String : Any]
                guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
                    print("Not containing JSON")
                    return
                }
    
                print("gotten json response dictionary is \n \(json)")
                // update UI using the response here
            }
    
            // execute the HTTP request
            task.resume()
    
        }
    

    NSURLConnection send User-Agent by default.
    default User-Agent style like.

    "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
    

    We can customize the User-Agent.

    urlRequest.setValue("URLConnection zgpeace User-Agent", forHTTPHeaderField: "User-Agent")
    

    I write a demo for URLConnection in the below.

    func requestUrlConnectionUserAgent() {
        print("requestUrlConnectionUserAgent")
    
        let url = URL(string: "https://httpbin.org/anything")!
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = "GET"
        // default User-Agent: "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
        urlRequest.setValue("URLConnection zgpeace User-Agent", forHTTPHeaderField: "User-Agent")
    
        NSURLConnection.sendAsynchronousRequest(urlRequest, queue: OperationQueue.main) { (response, data, error) in
            // ensure there is no error for this HTTP response
            guard error == nil else {
                print ("error: \(error!)")
                return
            }
    
            // ensure there is data returned from this HTTP response
            guard let content = data else {
                print("No data")
                return
            }
    
            // serialise the data / NSData object into Dictionary [String : Any]
            guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
                print("Not containing JSON")
                return
            }
    
            print("gotten json response dictionary is \n \(json)")
            // update UI using the response here
        }
    
      }
    

    Demo in github:
    https://github.com/zgpeace/UserAgentDemo.git

提交回复
热议问题