OSX 10.10 WKWebView UserAgent Suite (Swift)

I tried to install a custom UserAgent for WKWebView in my Mac application. Unfortunately, the specified user string will never be set. With the iOS SDK, this is not a big problem.

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

But this does not work with the Mac SDK. 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)

Thank you for any help.

+4
source share
2 answers

You must open some private WKWebView methods in the ObjC bridge header and call them to change the UA.

Adapted fragments from my mini browser :

jumper 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))
+4
source

, Swift 2, Obj-C API .

:

  let webView = WKWebView()
  webView.performSelector("_setApplicationNameForUserAgent:", withObject: "My App User Agent addition")

. -:)

+4

All Articles