zoukankan      html  css  js  c++  java
  • WKWebView和UIWebView 分别设置全局UserAgent

    WKWebView 设置全局UserAgent

    关键是要设置customUserAgent(>=iOS 9.0),否则执行evaluateJavaScript:@"navigator.userAgent"获取不到webView的UA:

    //修改userAgent
    + (void)addToWebViewUserAgent:(NSString *)addAgent
    {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            WKWebView *webView = [WKWebView new];
            [webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable oldAgent, NSError * _Nullable error) {
                if (![oldAgent isKindOfClass:[NSString class]]) {
                    // 为了避免没有获取到oldAgent,所以设置一个默认的userAgent
                    // Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148
                    oldAgent = [NSString stringWithFormat:@"Mozilla/5.0 (%@; CPU iPhone OS %@ like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148", [[UIDevice currentDevice] model], [[[UIDevice currentDevice] systemVersion] stringByReplacingOccurrencesOfString:@"." withString:@"_"]];
                }
                
                //自定义user-agent
                if (![oldAgent hasSuffix:addAgent]) {
                    NSString *newAgent = [oldAgent stringByAppendingFormat:@" DWD_HSQ/%@",addAgent];
                    [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":newAgent}];
                    // 一定要设置customUserAgent,否则执行navigator.userAgent拿不到oldAgent
                    webView.customUserAgent = newAgent;
                }
            }];
        });
    }


    UIWebView 设置全局UserAgent(建议使用WKWebView)

        // 修改全局UserAgent值
        UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
        NSString *userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
        NSString *newUserAgent = [userAgent stringByAppendingString:@" xxx"];//自定义需要拼接的字符串
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:newUserAgent, @"UserAgent", nil];
        [[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

    参考:https://www.jianshu.com/p/6d243781f368

  • 相关阅读:
    hdu 1042 N!
    hdu 1002 A + B Problem II
    c++大数模板
    hdu 1004 Let the Balloon Rise
    hdu 4027 Can you answer these queries?
    poj 2823 Sliding Window
    hdu 3074 Multiply game
    hdu 1394 Minimum Inversion Number
    hdu 5199 Gunner
    九度oj 1521 二叉树的镜像
  • 原文地址:https://www.cnblogs.com/ljcgood66/p/13161957.html
Copyright © 2011-2022 走看看