在WKWebview中设置useragent

时间:2014-11-18 12:34:14

标签: ios user-agent wkwebview

如何在WKWebView中设置自定义的useragent字符串?我试图嵌入我的应用版本,以便我的服务器端可以看到可用的功能。我找到了以下方法:

let userAgent = "MyApp/1.33.7"
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
    let content = NSString(data: data, encoding: NSUTF8StringEncoding)
    self.web!.loadHTMLString(content!, baseURL: url)
}
self.web!.loadRequest(request);

但这意味着只为该单个请求设置了useragent。第一个其他请求(例如转发)将意味着再次将useragent重置为默认值。如何更永久地配置wkwebview以使用我的自定义useragent字符串?

6 个答案:

答案 0 :(得分:57)

您会很高兴听到WKWebView在[{1}}和customUserAgent

中获得了iOS 9财产

示例:

OSX 10.11

答案 1 :(得分:19)

<强>更新

从iOS 9.0开始,可以直接设置用户代理(如其他答案中所述)。但重要的是要注意,设置它将完全覆盖默认用户代理。如果由于某种原因您需要添加自定义用户代理,请使用以下方法之一。

webView.evaluateJavaScript("navigator.userAgent") { [weak webView] (result, error) in
    if let webView = webView, let userAgent = result as? String {
        webView.customUserAgent = userAgent + "/Custom Agent"
    }
}

或使用牺牲UIWebView

webView.customUserAgent = (UIWebView().stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? "") + "/Custom agent"

<小时/> 旧回答:

如我的评论中所述,您可以使用与此处所述相同的方法:Change User Agent in UIWebView (iPhone SDK)

现在,如果你想获得用户代理,你需要有一个WKWebView的实例并在其上评估这个javascript:

navigator.userAgent

问题是,如果在实例化WKWebView之后设置自定义用户代理,您将始终获得相同的用户代理。要解决此问题,您必须重新实例化Web视图。下面是一个示例:

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);
    }];
}];

上面的代码将记录:

Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411 Appended Custom User Agent

替代

通过使用&#34;牺牲&#34;可以使这更简单。 UIWebView,因为它同步评估javascript。

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);
}];

记录同样的事情:

Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411 Appended Custom User Agent

现在UIWebView和WKWebView使用相同的用户代理,但如果将来发生变化,这种方法可能会导致问题。

答案 2 :(得分:5)

自定义用户代理

要设置自定义用户代理,您可以使用customUserAgent属性:

let webConfiguration = WKWebViewConfiguration()
let webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.customUserAgent = "ExampleApp/1.0 (iPhone)"

可用:iOS 9 +

附加到默认用户代理

要在默认用户代理的和,附加自定义字符串,您可以使用applicationNameForUserAgent属性:

let webConfiguration = WKWebViewConfiguration()
webConfiguration.applicationNameForUserAgent = "ExampleApp/1.0 (iPhone)"
let webView = WKWebView(frame: .zero, configuration: webConfiguration)

然后它会查找例如:

Mozilla/5.0 (iPhone; CPU iPhone OS 11_2 like Mac OS X) AppleWebKit/604.4.7
(KHTML, like Gecko) ExampleApp/1.0 (iPhone)
                    ^^^^^^^^^^^^^^^^^^^^^^^

可用:iOS 9 +

答案 3 :(得分:0)

let userAgentValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.1.1 Safari/603.2.4" webView.customUserAgent = userAgentValue Swift 3示例:

WKWebView

请注意那些尝试使用Storyboard或Interface Builder执行此操作的人:不幸的是,Xcode当前不支持在Storyboards(Xcode版本8.3.2)中使用UIWebView,因此您必须手动添加Web视图在你的代码中。

UserDefaults.standard.register(defaults: ["UserAgent": userAgentValue]) Swift 3示例:

%

答案 4 :(得分:0)

在我的swift 3案例中,我需要使用自定义userAgent的整个应用程序,这是我在AppDelegate中的解决方案。这里使用UIWebview是因为我不需要设置 WKWebViewConfiguration ,因为我只需要userAgent字符串

 fileprivate func setupGlobalWebviewUserAgent() {

    let webview = UIWebView()
    var newUserAgent = webview.stringByEvaluatingJavaScript(from: "navigator.userAgent")
    newUserAgent = newUserAgent?.appending("custom user agent")
    let dictionary = Dictionary(dictionaryLiteral: ("UserAgent", newUserAgent))
    UserDefaults.standard.register(defaults: dictionary)
}

答案 5 :(得分:0)

WKWebView中的默认User-Agent为

Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X)

您可以自定义WKWebView用户代理

webView.customUserAgent = "zgpeace User-Agent"

我为WKWebView编写了一个演示:

func requestWebViewAgent() {
        print("requestWebViewAgent")

        let webView = WKWebView()
        webView.evaluateJavaScript("navigator.userAgent") { (userAgent, error) in
            if let ua = userAgent {
                print("default WebView User-Agent > \(ua)")
            }

            // customize User-Agent
            webView.customUserAgent = "zgpeace User-Agent"
        }
    }

警告:发布webView时,webView中的“ User-Agent”为零。您可以将webView对象设置为属性以保留webView。

NSURLSession默认发送用户代理
默认为User-Agent样式。

"User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";

我们可以自定义User-Agent。

let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = ["User-Agent": "zgpeace User-Agent"]

我在下面为URLSession编写了一个演示。

     func requestUrlSessionAgent() {
        print("requestUrlSessionAgent")

        let config = URLSessionConfiguration.default
        // default User-Agent: "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
        // custom User-Agent
        config.httpAdditionalHeaders = ["User-Agent": "zgpeace User-Agent"]
        let session = URLSession(configuration: config)

        let url = URL(string: "https://httpbin.org/anything")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"

        let task = session.dataTask(with: url) { data, response, error in

            // ensure there is no error for this HTTP response
            guard error == nil else {
                print ("error: \(error!)")
                return
            }

            // ensure there is data returned from this HTTP response
            guard let content = data else {
                print("No data")
                return
            }

            // serialise the data / NSData object into Dictionary [String : Any]
            guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
                print("Not containing JSON")
                return
            }

            print("gotten json response dictionary is \n \(json)")
            // update UI using the response here
        }

        // execute the HTTP request
        task.resume()

    }

NSURLConnection默认发送用户代理
默认为User-Agent样式。

"User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";

我们可以自定义User-Agent。

urlRequest.setValue("URLConnection zgpeace User-Agent", forHTTPHeaderField: "User-Agent")

我在下面为URLConnection编写了一个演示。

func requestUrlConnectionUserAgent() {
    print("requestUrlConnectionUserAgent")

    let url = URL(string: "https://httpbin.org/anything")!
    var urlRequest = URLRequest(url: url)
    urlRequest.httpMethod = "GET"
    // default User-Agent: "User-Agent" = "UserAgentDemo/1 CFNetwork/1121.2.1 Darwin/19.2.0";
    urlRequest.setValue("URLConnection zgpeace User-Agent", forHTTPHeaderField: "User-Agent")

    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: OperationQueue.main) { (response, data, error) in
        // ensure there is no error for this HTTP response
        guard error == nil else {
            print ("error: \(error!)")
            return
        }

        // ensure there is data returned from this HTTP response
        guard let content = data else {
            print("No data")
            return
        }

        // serialise the data / NSData object into Dictionary [String : Any]
        guard let json = (try? JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [String: Any] else {
            print("Not containing JSON")
            return
        }

        print("gotten json response dictionary is \n \(json)")
        // update UI using the response here
    }

  }

GitHub中的演示:
https://github.com/zgpeace/UserAgentDemo.git