Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OSX 10.10 WKWebView set UserAgent (Swift)

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.

like image 982
Darx Avatar asked Feb 12 '23 02:02

Darx


2 Answers

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:

bridging-header.h

// 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

macpin.swift

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))
like image 57
kfix Avatar answered Feb 13 '23 19:02

kfix


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 :)

like image 27
Andrew Vyazovoy Avatar answered Feb 13 '23 20:02

Andrew Vyazovoy