Reputation: 356
I'm having trouble setting a custom user-agent for my webview in the demo I am just trying to set it to my Safari user-agent. It is seemingly very difficult to find examples of how to go about doing this in a swift based osx cocoa application.
Here's my code:
import Cocoa
import WebKit
class ViewController: NSViewController {
@IBOutlet weak var webView: WebView!
@IBOutlet weak var progressIndicator: NSProgressIndicator!
override func viewDidAppear() {
super.viewDidAppear()
self.view.window?.titleVisibility = .Hidden
self.view.window?.titlebarAppearsTransparent = true
self.view.window?.styleMask |= NSFullSizeContentViewWindowMask
let urlString = NSURL(string: "http://whatsmyuseragent.com")
NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/600.7.12 (KHTML, like Gecko) Version/8.0.7 Safari/600.7.12"])
self.webView.mainFrame.loadRequest(NSMutableURLRequest(URL: urlString!))
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
override func webView(sender: WebView!, didStartProvisionalLoadForFrame frame: WebFrame!) {
self.progressIndicator.startAnimation(self)
}
override func webView(sender: WebView!, didFinishLoadForFrame frame: WebFrame!) {
self.progressIndicator.stopAnimation(self)
}
override func mouseEntered(event: NSEvent) {
}
}
Also I have seen UIWebView iOS5 changing user-agent the code example given seemingly does not do anything and/or I am putting it in the wrong place. I have 2 files "AppDelegate.swift" and "ViewController.swift" I have tried the code at various places in both files to no avail.
Thanks!
Upvotes: 2
Views: 3556
Reputation: 5306
The important properties for this are WebView customUserAgent:
and WebView applicationNameForUserAgent:
.
To replace the entire User-Agent string with a new one:
webView.customUserAgent = "MyAgent/1.0.0"
To append your app string onto the existing user agent string:
webView.applicationNameForUserAgent = "MyAgent/1.0.0"
Further details: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/Spoofing.html
Upvotes: 1