Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I prevent the “User Agent” header of a WKWebView from changing?

    let url =  NSURL(string:"http://www.examplepage.com/“)
            let Request = NSMutableURLRequest(URL: url!)


            Request.setValue("Custom-Agent", forHTTPHeaderField: "User-Agent")

            let task1 = NSURLSession.sharedSession().dataTaskWithRequest(Request){ data, response, error in

                let contentPage =  NSString(data: data!, encoding: NSUTF8StringEncoding)
                self.webView!.loadHTMLString(contentPage! as String, baseURL: url)

            }
            task1.resume()

I’ve used the following code to set the “User Agent” header of a WKWebView.

It works well when the app first loaded, but only after a button is clicked into the link the “User-Agent” changes.

How can I prevent the "User-Agent" from changing?

like image 551
S.D Avatar asked Oct 30 '25 09:10

S.D


1 Answers

  1. For iOS 9, use the customUserAgent property on the web view.

  2. For iOS 8 and earlier, do this instead:

    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "BlahBlahBlah"])

like image 175
dgatwood Avatar answered Nov 02 '25 18:11

dgatwood