2019-01-11UIWebView&WKWebView的UA设置

pragma mark - 全局修改UA 一般写到 appdelegate 的 didfinishlaunch 方法中 一次设置 全局生效

-(void)modificationUA{
NSString *currentUserAgent = [NSString stringWithFormat:@"%@/%@",[[TEnvConfig shareInstance] getWebViewUserAgentPreffix],APP_VERSION];
// get original UserAgent string by using temporal UIWebView WKWebView
UIWebView *tmp = [[UIWebView alloc] init];
NSString *originalUA = [tmp stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];

// create custom UserAgent string
NSString *customUA = [NSString stringWithFormat:@"%@ %@", originalUA, currentUserAgent];
NSLog(@"newUA:%@",customUA);
// set custom UserAgent as default
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:customUA , @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

}

利用uiwebview
NSString *originalUA = [tmp stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
获取 originalUA 肯定能获取到 ,而且利用NSUserDefaults 可以全局生效 不论是 uiwebview还是wkwebview

利用wkwebview
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id __nullable userAgent, NSError * __nullable error) {
NSLog(@"navigator.userAgent: %@", userAgent);
如果在这里在原来的 UserAgent 基础上 修改的话 UserAgent可能是nil 或者有error 导致无法设置成功
}];

另外
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.applicationNameForUserAgent = @"UserAgent-Name";
也可以修改userAgent 但是只能单次生效 无法全局生效

你可能感兴趣的:(2019-01-11UIWebView&WKWebView的UA设置)