Skip to content

Commit 1e62b8f

Browse files
committed
feature (User-Agent): Added Support for WKWebView
1 parent fcd3840 commit 1e62b8f

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

CordovaLib/Classes/Private/Plugins/CDVWebViewEngine/CDVWebViewEngine.m

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,32 @@ - (WKWebViewConfiguration*) createConfigurationFromSettings:(NSDictionary*)setti
108108
}
109109
configuration.allowsAirPlayForMediaPlayback = allowsAirPlayForMediaPlayback;
110110

111+
/*
112+
* Sets Custom User Agents
113+
* - (Default) "userAgent" is set the the clean user agent.
114+
* E.g.
115+
* UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"
116+
*
117+
* - If "OverrideUserAgent" is set, it will overwrite the entire "userAgent" value. The "AppendUserAgent" will be iggnored if set.
118+
* Notice: The override logic is handled in the "pluginInitialize" method.
119+
* E.g.
120+
* OverrideUserAgent = "foobar"
121+
* UserAgent = "foobar"
122+
*
123+
* - If "AppendUserAgent" is set and "OverrideUserAgent" is not set, the user defined "AppendUserAgent" will be appended to the "userAgent"
124+
* E.g.
125+
* AppendUserAgent = "foobar"
126+
* UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 foobar"
127+
*/
128+
NSString *userAgent = configuration.applicationNameForUserAgent;
129+
if (
130+
[settings cordovaSettingForKey:@"OverrideUserAgent"] == nil &&
131+
[settings cordovaSettingForKey:@"AppendUserAgent"] != nil
132+
) {
133+
userAgent = [NSString stringWithFormat:@"%@ %@", userAgent, [settings cordovaSettingForKey:@"AppendUserAgent"]];
134+
}
135+
configuration.applicationNameForUserAgent = userAgent;
136+
111137
return configuration;
112138
}
113139

@@ -149,6 +175,15 @@ - (void)pluginInitialize
149175
// re-create WKWebView, since we need to update configuration
150176
WKWebView* wkWebView = [[WKWebView alloc] initWithFrame:self.engineWebView.frame configuration:configuration];
151177
wkWebView.UIDelegate = self.uiDelegate;
178+
179+
/*
180+
* This is where the "OverrideUserAgent" is handled. This will replace the entire UserAgent
181+
* with the user defined custom UserAgent.
182+
*/
183+
if ([settings cordovaSettingForKey:@"OverrideUserAgent"] != nil) {
184+
wkWebView.customUserAgent = [settings cordovaSettingForKey:@"OverrideUserAgent"];
185+
}
186+
152187
self.engineWebView = wkWebView;
153188

154189
if ([self.viewController conformsToProtocol:@protocol(WKUIDelegate)]) {

0 commit comments

Comments
 (0)