赵洪武
赵洪武

Reputation: 121

iOS 12 WKWebview set customUserAgent not work?

It seems there is a bug in iOS 12 when set wkwebview customUserAgent. In webView:didFinishNavigation: method I print customUserAgent and compare with webivew.evaluateJavaScript result.It is different.

NSLog(@"user-agent is %@"); //Get a custom user-agent
[self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
    NSLog(@"user-agent is %@", result); //Get a default  user-agent
}];

Dose anyone see the same problem?

Upvotes: 1

Views: 6983

Answers (5)

xiao333ma
xiao333ma

Reputation: 101

iOS 12, if you call like this to modify you UA, it will not work

[self.wkWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(NSString* _Nullable oldUA, NSError * _Nullable error) {


    // modify ua
    self.wkWebView.customUserAgent = @"you custom ua";

}];

Once you call navigator.userAgent, you can never modify it. So you need a fakeWKWebView to get the default UA and set to you truly WKWebView

self.fakeWKWebView = [[WKWebView alloc] init];

[self.fakeWKWebView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(NSString* _Nullable oldUA, NSError * _Nullable error) {
    self.fakeWKWebView = nil;

    // modify ua
    self.wkWebView.customUserAgent = @"you custom ua";

}];

Upvotes: 1

Jesuslg123
Jesuslg123

Reputation: 735

I have found the same issue, here is the screen capture. Seem an iOS 12 issue with WKWebView.

enter image description here

Upvotes: 0

user2116267
user2116267

Reputation: 1

Add this to AppDelegate

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

Upvotes: -4

Sachin Selvaraj
Sachin Selvaraj

Reputation: 1

The above suggested answer doesn't seem to be working for me.

Setting the custom user agent using the below code works on the simulator but not on the actual device, both running iOS 12.0 Beta.

webView.customUserAgent = [NSString stringWithFormat:@"%@ %@", userAgent, @"custom agent"];

Upvotes: 0

赵洪武
赵洪武

Reputation: 121

Finally, I find the problem is that you can not change the customUserAgent after calling its evaluateJavaScript: metthod in iOS 12. Here is my code

self..webView.evaluateJavaScript("navigator.userAgent") { [weak self] (result, error) in
            self?.webView.customUserAgent = result as? String + "customAgent" //not work
        }
    }

You can initialize a UIWebview or another WKWebiview to get the current user-agent and append your custom user-agent after it.

self.tempWebView.evaluateJavaScript("navigator.userAgent") { [weak self] (result, error) in
        if self == nil || error != nil {
            return
        }
        if let userAgent = result as? String {
            self?.webView.customUserAgent = userAgent + "custom agent"
        }
    }

Upvotes: 10

Related Questions