i tried to set a Custom UserAgent for the WKWebView in my Mac App. Unfortunately the specified Custom String never gets set. With the iOS SDK it's not a big deal
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent" : "Custom Agent"])
But with the Mac SDK it does not work. I also tried
let url = NSURL(string: startURL)
let req = NSMutableURLRequest(URL: url!)
req.setValue("Custom Agent/1.0", forHTTPHeaderField: "User-Agent")
webView!.loadRequest(req)
Thanky you for every help.
You have to expose some private methods of WKWebView in your ObjC bridging header and call them to change the UA.
Adapted snippets from my mini-browser app:
// https://github.com/WebKit/webkit/blob/master/Source/WebKit2/UIProcess/API/Cocoa/WKWebViewPrivate.h
@import WebKit;
@interface WKWebView (Privates)
@property (copy, setter=_setCustomUserAgent:) NSString *_customUserAgent;
@property (copy, setter=_setApplicationNameForUserAgent:) NSString *_applicationNameForUserAgent;
@property (nonatomic, readonly) NSString *_userAgent;
@end
if let agent = withAgent? {
webview._customUserAgent = agent // specify full UA
} else {
webview._applicationNameForUserAgent = "Version/8.0.2 Safari/600.2.5"
// appended to UA, mimicing Safari
}
webview.loadRequest(NSURLRequest(URL: url))
Now, in Swift 2, you can do it without Obj-C with help of new selector API.
Like this:
let webView = WKWebView()
webView.performSelector("_setApplicationNameForUserAgent:", withObject: "My App User Agent addition")
But avoid to use it in production code in this form. Try to hide it somehow :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With