0
点赞
收藏
分享

微信扫一扫

WKWebView设置User-Agent的正确姿势

其生 2022-02-14 阅读 56
ioswebview

如何设置WKWebView的User-Agent

iOS 9.0 和 macos 10.11, WebKit 的 WKWebViewConfiguration 这个类中新增了一个属性 applicationNameForUserAgent。

/*! @abstract The name of the application as used in the user agent string.
*/
@property (nullable, nonatomic, copy) NSString *applicationNameForUserAgent API_AVAILABLE(macos(10.11), ios(9.0));

这个注释也是写的模棱两可的,查了下文档,是这样描述的:

The user-agent is used by websites to identify the client browser.

设置 user-agent,js 以此来识别客户端浏览器。说简单点就是客户端通过设置 user-agent 的值,让 js 端能从中得知客户端浏览器是iOS,还是安卓,在iPad上还是别的网页浏览器上。

设置的一些特殊标识,一般大都是 iOS,Andriod,版本号等关键信息,通过设置这些信息,js 获取到user-agent从而判断客户端浏览器类型。

iOS 9.0 以及之后设置 user-agent 的正确姿势如下:

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.applicationNameForUserAgent = @"iOS iPad 21.00 xxx";
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];

这样设置简洁有效,设置完成之后,会在系统的user-agent后面拼上我们设置的内容,并不会取代原来的设置。

在这里插入图片描述

iOS 9.0 之前是怎么设置user-agent的呢?

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *version = @"xxx";
        if (![result containsString:version]) {
            NSString *deviceIdentifier = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) ? @"iPad" :@"iPhone";
            webView.customUserAgent = [NSString stringWithFormat:@"%@ %@ %@ %@",result, @"iOS xxx", version, deviceIdentifier];
        }
        NSLog(@"user-Agent : %@",webView.customUserAgent);
    }];
}

需要在WebView加载完成之后的的回调中,通过 evaluateJavaScript 获取 js 中 navigator.userAgent 的值,并拼接我们上我们需要设置的其他内容。

如果获取到的navigator.userAgent中已经设置过了我们需要设置的信息的话,就不再重复设置。这个函数每当webView加载完都会回调,这样丛可以避免重复的在userAgent后面追加设置iOS xxx,version等信息。

iOS 9 以及之后不要通过 evaluateJavaScript:@“navigator.userAgent” 这种设置方式userAgent,第一次设置会不成功,需要重新刷新一下webView才能设置成功。

很久之前我记得还在适配iOS 8的时候并不会出现这个问题,但是今天我用iOS 15的设置再通过这种方式来设置的时候发现总是设置无效,调试时,刷新了一下能设置上。

所以如果你的项目最低设配版本已经高于iOS9.0的话,直接删除多余的代码,使用applicationNameForUserAgent就好。

举报

相关推荐

0 条评论