Reputation: 1049
I have UIWebView where i need to change Navigator userAgent property.
For iOS version 10+ code below works perfectly:
func webViewDidFinishLoad(_ webView: UIWebView) {
let script = "window.navigator.__defineGetter__('userAgent', function() " +
"{ return '+keys +thatIs +neededTo +add'; });"
webView.stringByEvaluatingJavaScript(from: script)
}
But with iOS9 this doesn't work.
Does anyone have any idea?
In Info.plist I have set NSAllowsArbitraryLoads
to true.
Upvotes: 0
Views: 556
Reputation: 1253
The user agent needs to be set in the UserDefaults. You can use the following code to set it up.
func setUserAgent(as userAgentString: String) {
UserDefaults.standard.register(defaults: ["UserAgent": userAgentString])
}
Usage:
let userAgentString = "USER AGENT STRING HERE"
setUserAgent(as: userAgentString)
EDIT:
I see that you want to append some string to the current UserAgent. For that you need to read the value for the current user agent, store it, add your custom string, then store the new user agent. Usage stays the same.
func setUserAgent(as value: String) {
let webView = UIWebView(frame: CGRect(width: 0, height: 0))
let defaultUserAgentString = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")
UserDefaults.standard.register(defaults: ["UserAgent": defaultUserAgentString + " " + value])
// remove the " " space if you don't need it
}
EDIT 2:
Yes, changing it will change it for all the web views across your app. To avoid this you can...
func setUserAgent(as value: String) {
let webView = UIWebView()
Constants.defaultUserAgentString = webView.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
UserDefaults.standard.register(defaults: ["UserAgent": defaultUserAgentString + " " + value])
}
func resetUserAgent() {
if let defaultString = Constants.defaultUserAgentString {
UserDefaults.standard.register(defaults: ["UserAgent": defaultString])
}
}
Constants
here is a struct/class that is used to store global constants, you may replace it with your own struct/class if you have one. Just add static variable defaultUserAgentString
to keep track of the default user agent.
Use resetUserAgent()
to switch back to the default user agent when you done. Maybe add it to viewWillDisappear(
) on the ViewController
handling the WebView
that needs the modified user agent.
Upvotes: 1