iOS

ios修改本地useragent(WKWebView)

ios修改本地useragent(WKWebView)

1、获取原先的userAgent;

1
2
3
4
5
6
/* @abstract Evaluates the given JavaScript string.
@param javaScriptString The JavaScript string to evaluate.
@param completionHandler A block to invoke when script evaluation completes or fails.
@discussion The completionHandler is passed the result of the script evaluation or an error.
*/
- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;

这个方法也可以用来解决Native调用JS的问题。

原生js中获取userAgent的方法就是”navigator.userAgent”。

2、修改userAgent;

1
2
3
/*! @abstract The custom user agent string or nil if no custom user agent string has been set.
*/
@property (nullable, nonatomic, copy) NSString *customUserAgent API_AVAILABLE(macosx(10.11), ios(9.0));

WKWebView 类有个customUserAgent属性,赋值即可。

3、UIWebView里面userAgent的修改方法;

由于UIWebView有内存泄露问题,不可控,建议大家也使用WKWebView,替换成本还是很小的。

4、坑;

大多数人,包括网上很多帖子都写了关于wkweb修改useragent的方法,例如

https://www.jianshu.com/p/fd6fe72a3b0e

https://www.jianshu.com/p/5f02451b8e87

这两篇文章是百度搜索的前几个,都提到了修改不生效,“??需要alloc两遍??”,还有人提到“??第一次进入不生效,第二次就ok了??”。

仔细看下来不难发现,WKWebView获取userAgent是个异步block过程,那修改userAgent也是在异步里面完成的,既然修改过程是异步,name使用不得等block回调完成再使用么。

全量代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//
// DocumentViewController.m
// Project_20171206
//
// Created by StephenZhu on 2018/5/14.
// Copyright © 2018年 StephenZhu. All rights reserved.
//

#import "DocumentViewController.h"
#import <WebKit/WebKit.h>
@interface DocumentViewController ()
@property (nonatomic,strong) WKWebView *myWebView;
@end

@implementation DocumentViewController

- (void)viewDidLoad {
[super viewDidLoad];
[self.view addSubview:self.myWebView];
[self layoutMain];
[self setUserAgent];
}
- (void)layoutMain
{
[self.myWebView mas_makeConstraints:^(MASConstraintMaker *make) {
make.edges.mas_equalTo(0);
}];
}
- (void)loadUrl
{
NSString* urlStr = [NSString stringWithFormat:@"http://WWW.BAIDU.COM"];
NSURL *url = [NSURL URLWithString:urlStr];
[self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSLog(@"%@",result);
[self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];
}];

}
- (void)setUserAgent
{
[self.myWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
NSString *oldUserAgent = result;
NSString *newUserAgent = [NSString stringWithFormat:@"%@ %@",oldUserAgent,@"TheNewWordForUserAgent/v1.6"];
self.myWebView.customUserAgent = newUserAgent;
[self loadUrl];
}];
}
#pragma mark - lazyload
- (WKWebView *)myWebView
{
if (_myWebView == nil) {
_myWebView = [[WKWebView alloc]initWithFrame:CGRectZero];
}
return _myWebView;
}
@end