简体   繁体   中英

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

How do you change the user agent used by WKWebview ?

With the older WebView , I could write the following to change the user agent:

[myWebView setCustomUserAgent:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4)
 AppleWebKit/537.77.4 (KHTML,like Gecko) Version/7.0.5 Safari/537.77.4"];

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

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 request
let 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)
}

It wouldn't be ideal but you could likely implement a custom NSURLProtocol handler to intercept HTTP requests and modify them with your custom user-agent header. I don't think this would work on iOS since WKWebView makes requests out-of-process and bypasses any registered NSURLProtocols. But it might work on OS X?

With a user entered URL in a text field, you can completely control the NSURLRequest using an NSMutableURLRequest object, and set the header field for it.

However, with things the user actually clicks on within the web view, you're kind of not in control from obvious and clearly documented Objective-C land. I do not see any documented way beyond what WKWebView seems to push things toward, JavaScript. So, that means you can do things like posted here: Mocking a useragent in javascript? Using the script injection APIs.

This is why I do not like WKWebView. I want to like it, but I do not want to learn to do half of everything in JavaScript.

So, you can create a WKUserScript object to do this, and set its injection time to WKUserScriptInjectionTimeAtDocumentStart. That will enable you to handle things requested from page elements within the document, as long as the page itself is not loading other scripts that conflict.

First Quit Safari. Then open Terminal and paste this command, and press enter:

defaults write com.apple.Safari CustomUserAgent "\\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/538.46 (KHTML, like Gecko) Version/7.1 Safari/537.85.7\\""

Open Safari and you're done.

To undo this change, close Safari and paste this command into terminal:

defaults delete com.apple.Safari CustomUserAgent

Sometimes a restart may be required to get these changes to stick, not sure why, could be a cache thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM