Customize the user agent in WebView (iOS)¶
Use the key UserAgent
in NSUserDefaults to customize your user agent. Please perform the customization once only during the app launch and before any instantiation of UIWebView or WKWebView.
The following is an example adding the string MY_CUSTOM_USER_AGENT
to the beginning of the original user agent.
// get original UserAgent string by using temporal UIWebView
UIWebView *tmp = [[UIWebView alloc] init];
NSString *originalUA = [tmp stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
// create custom UserAgent string
NSString *customUA = [NSString stringWithFormat:@"%@ %@", @"MY_CUSTOM_USER_AGENT", originalUA];
// set custom UserAgent as default
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:customUA , @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
// get original UserAgent string by using temporal UIWebView
let tmp = UIWebView()
let originalUA = tmp.stringByEvaluatingJavaScript(from: "navigator.userAgent")!
// create custom UserAgent string
let customUA = "MY_CUSTOM_USER_AGENT \(originalUA)"
// set custom UserAgent as default
UserDefaults.standard.register(defaults: ["UserAgent": customUA])