How do I change the WKWebview's user agent in OS X Yosemite? How do I change the WKWebview's user agent in OS X Yosemite? xcode xcode

How do I change the WKWebview's user agent in OS X Yosemite?


Very simple in Swift. Just place the following into your App DelegatedidFinishLaunchingWithOptions.

NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "Custom Agent"])

If you want to append to the existing agent string then:

let userAgent = UIWebView().stringByEvaluatingJavaScriptFromString("navigator.userAgent")! + " Custom Agent"NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : userAgent])

Note: You will need to uninstall and reinstall the App to avoid appending to the existing agent string.


I don't have an answer for this. However, some pointers from my research so far:

In iOS, it's possible to set a custom user agent for a UIWebView like this:

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:agent, @"UserAgent", nil];[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

In OSX, there was a setCustomUserAgent method for WebView elements that did the trick.

However, this doesn't work for WKWebView (at least, in OSX). I couldn't find any documentation about it from Apple, either.

Hope somebody can help!


I ran into the same issue, but managed to work around it using a combination of loadHTMLString on the WKWebView and a NSMutableURLRequest to do the heavy lifting.

My search on how to call some method on the WKWebView itself lead me to http://trac.webkit.org/changeset/165594, which implies there is a private method _setCustomUserAgent to do this. I'm not proficient enough in cocoa/swift to figure this one out.

I ended up using the code below, as I really only need to fetch the contents of a single URL and display it, but it may be helpful in some way.What it does is simply loading the contents of an URL into the WKWebView as string, I suspect you may lose back/forward navigation and such, and it will only work for the initial page display, as the WKWebView will take over clicks and asset loading.

(please note, this example is written in Swift and not Objective-C)

self.webView = WKWebView(frame: webViewRect, configuration: webViewConfig)//  create the requestlet url = NSURL(string: "https://example.com/")let request = NSMutableURLRequest(URL: url!)request.setValue("YourUserAgent/1.0", forHTTPHeaderField: "User-Agent")NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in    let content = NSString(data: data, encoding: NSUTF8StringEncoding)    self.webView!.loadHTMLString(content!, baseURL: url)}