ios 在 WKWebview 中设置用户代理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26994491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:40:29  来源:igfitidea点击:

Set useragent in WKWebview

iosuser-agentwkwebview

提问by Pvel

How do I set a custom useragent string in a WKWebView? I'm trying to embed the version of my app so that my server-side can see what features are available. I found the following method:

如何在 WKWebView 中设置自定义用户代理字符串?我正在尝试嵌入我的应用程序版本,以便我的服务器端可以看到哪些功能可用。我找到了以下方法:

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

But this means the useragent is only set for that single request. The first other request (e.g. a forward), will mean the useragent is reset to default again. How can I more permanently configure the wkwebview to use my custom useragent string?

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

回答by Erik Aigner

You'll be happy to hear that WKWebViewjust gained a customUserAgentproperty in iOS 9and OSX 10.11

你会很高兴听到WKWebView刚刚customUserAgentiOS 9OSX 10.11

Example:

例子:

wkWebView.customUserAgent = "your agent" 

回答by Nikola Lajic

Update:

更新:

As of iOS 9.0 it is possible to set the user agent directly (as stated in other answers). But it is important to note that setting it will completely override the default user agent. If for some reason you need to just append a custom user agent use one of the following approaches.

从 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"
    }
}

or by using a sacrificial UIWebView

或者通过使用牺牲 UIWebView

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



Old answer:旧答案:

As noted in my comment you can use the same approach as described here: Change User Agent in UIWebView (iPhone SDK)

正如我在评论中指出的,您可以使用与此处描述的相同的方法:在 UIWebView (iPhone SDK) 中更改用户代理

Now if you want to get the user agent you need to have an instance of a WKWebView and evaluate this javascript on it:

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

navigator.userAgent

The problem is that if you set a custom user agent after a WKWebView has been instantiated you will always get the same user agent. To solve this problem you have to reinstantiate the web view. Here is a sample how this might look:

问题是,如果在实例化 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);
    }];
}];

The code above will log:

上面的代码将记录:

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

Alternative

选择

This could be made even simpler by using a "sacrificial" UIWebView since it evaluates javascript synchronously.

这可以通过使用“牺牲” 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);
}];

Which logs the same thing:

哪个记录了同样的事情:

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

Right now UIWebView and WKWebView use the same user agent but this approach might cause problems if that changes in the future.

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

回答by Marián ?erny

Custom User Agent

自定义用户代理

To set a custom User Agent you can use customUserAgentproperty:

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

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

Available: iOS 9+

可用:iOS 9+

Append to the default User Agent

附加到默认用户代理

To append a custom string at the and of the default user agent you can use applicationNameForUserAgentproperty:

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

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

Then it will look for example like:

然后它将看起来像:

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

Available: iOS 9+

可用:iOS 9+

回答by Alex

WKWebViewSwift 3 example:

WKWebView斯威夫特 3 示例:

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


Note to those who try to do this using Storyboard or Interface Builder: Unfortunately, Xcode doesn't currently support using WKWebViewin Storyboards (Xcode version 8.3.2), so you have to add the web view manually in your code.

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

UIWebViewSwift 3 example:

UIWebView斯威夫特 3 示例:

UserDefaults.standard.register(defaults: ["UserAgent": userAgentValue])

回答by Stephen Chen

In my swift 3 case, I need entire app using a custom userAgent, here is my solution in AppDelegate. Here using UIWebview is because I don't need to set up the WKWebViewConfiguration, because I just only need the userAgent string

在我的 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)
}

回答by Zgpeace

the default User-Agent in WKWebView is as

WKWebView 中的默认 User-Agent 为

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

You can customize the WKWebView User-Agent

您可以自定义 WKWebView User-Agent

webView.customUserAgent = "zgpeace User-Agent"

I write a demo for WKWebView:

我为 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"
        }
    }

Warning: "User-Agent" is nil from webView, when webView is released. You can set webView object as property to keep the webView.

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

NSURLSession send User-Agent by default.
default User-Agent style like.

NSURLSession 默认发送 User-Agent
默认的 User-Agent 风格,如。

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

We can customize the User-Agent.

我们可以自定义用户代理。

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

I write a demo for URLSession in the below.

我在下面为 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 send User-Agent by default.
default User-Agent style like.

NSURLConnection 默认发送 User-Agent
默认的 User-Agent 风格,如。

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

We can customize the User-Agent.

我们可以自定义用户代理。

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

I write a demo for URLConnection in the below.

我在下面为 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
    }

  }

Demo in github:
https://github.com/zgpeace/UserAgentDemo.git

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