ios 参考部分

WKWebview修改userAgent

2017-05-31  本文已影响1035人  大热天晒太阳

在混合开发中,难免会遇到需要服务器判断是否为app打开该网页
可以通过设置webview的userAgent实现判断

参考stackoverflow

UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
    NSLog(@"%@", result);
}];

这一种不使用Block,适合多个webView共用一个父类

self.wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds];
__weak typeof(self) weakSelf = self;
[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
    __strong typeof(weakSelf) strongSelf = weakSelf;

    NSString *userAgent = result;
    NSString *newUserAgent = [userAgent stringByAppendingString:@" Appended Custom User Agent"];

    NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

    strongSelf.wkWebView = [[WKWebView alloc] initWithFrame:strongSelf.view.bounds];

    // After this point the web view will use a custom appended user agent
    [strongSelf.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {
        NSLog(@"%@", result);
    }];
}];
上一篇下一篇

猜你喜欢

热点阅读