WKWebView+UserAgent.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //
  2. // WKWebView+UserAgent.m
  3. // Starbuds
  4. //
  5. // Created by 翟玉磊 on 2020/5/25.
  6. // Copyright © 2020 翟玉磊. All rights reserved.
  7. //
  8. #import "WKWebView+UserAgent.h"
  9. @implementation WKWebView (UserAgent)
  10. /// 设置自定义的Agent 和H5交互
  11. /// 一定要在初始化添加到父view后在调用才会生效
  12. - (void)setupCustomUserAgent {
  13. if (@available(iOS 12.0, *)){
  14. //由于iOS12的UA改为异步,所以不管在js还是客户端第一次加载都获取不到,所以此时需要先设置好再去获取(1、如下设置;2、先在AppDelegate中设置到本地)
  15. NSString *language = [NSString kcSeverLanguage];
  16. NSString *userAgent = [self valueForKey:@"applicationNameForUserAgent"];
  17. NSString *customUserAgent = [NSString stringWithFormat:@"%@/%@/lang:%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], APP_VERSION, language];
  18. NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@", userAgent, customUserAgent];
  19. [self setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
  20. }
  21. [self evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  22. NSString *userAgent = result;
  23. NSString *language = [NSString kcSeverLanguage];
  24. NSString *customUserAgent = [NSString stringWithFormat:@"%@/%@/lang:%@", [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"], APP_VERSION, language];
  25. NSLog(@"userAgent:%@", userAgent);
  26. if ([userAgent rangeOfString:customUserAgent].location != NSNotFound) {
  27. return ;
  28. }
  29. NSString *newUserAgent = [userAgent stringByAppendingString:customUserAgent];
  30. // NSLog(@"%@>>>%@>>>>>",userAgent,newUserAgent);
  31. NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent,@"UserAgent", nil];
  32. [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
  33. [[NSUserDefaults standardUserDefaults] synchronize];
  34. //不添加以下代码则只是在本地更改UA,网页并未同步更改
  35. if (@available(iOS 9.0, *)) {
  36. [self setCustomUserAgent:newUserAgent];
  37. } else {
  38. [self setValue:newUserAgent forKey:@"applicationNameForUserAgent"];
  39. }
  40. }];
  41. }
  42. @end