feat(apple): userAgent can be changed at runtime (#2116)

Make it so that if you change the userAgent prop, this change is propagated to
the native webview on iOS/macOS. Android already has this functionality.

Sometimes it is useful for WebView apps to be able to change their user agent
dynamically to communicate custom things to the web app they are hosting.
Since we can't add custom headers to every single request made by the webview,
the user agent can be used to send things like feature flags to the web app, so
it can have the appropriate behavior depending on what state the mobile app is
in.
This commit is contained in:
Tyler Coffman 2021-08-09 10:20:04 -07:00 committed by GitHub
parent 9d82aec237
commit 2fc86f9d39
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 4 deletions

View File

@ -311,9 +311,7 @@ static NSDictionary* customCertificatesForHost;
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
_webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
if (_userAgent) {
_webView.customUserAgent = _userAgent;
}
_webView.customUserAgent = _userAgent;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
_webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
@ -701,6 +699,12 @@ static NSDictionary* customCertificatesForHost;
}
#endif // !TARGET_OS_OSX
- (void)setUserAgent:(NSString*)userAgent
{
_userAgent = userAgent;
_webView.customUserAgent = userAgent;
}
- (void)setScrollEnabled:(BOOL)scrollEnabled
{
_scrollEnabled = scrollEnabled;

View File

@ -72,7 +72,6 @@ RCT_EXPORT_VIEW_PROPERTY(hideKeyboardAccessoryView, BOOL)
RCT_EXPORT_VIEW_PROPERTY(allowsBackForwardNavigationGestures, BOOL)
RCT_EXPORT_VIEW_PROPERTY(incognito, BOOL)
RCT_EXPORT_VIEW_PROPERTY(pagingEnabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(userAgent, NSString)
RCT_EXPORT_VIEW_PROPERTY(applicationNameForUserAgent, NSString)
RCT_EXPORT_VIEW_PROPERTY(cacheEnabled, BOOL)
RCT_EXPORT_VIEW_PROPERTY(allowsLinkPreview, BOOL)
@ -125,6 +124,10 @@ RCT_CUSTOM_VIEW_PROPERTY(useSharedProcessPool, BOOL, RNCWebView) {
view.useSharedProcessPool = json == nil ? true : [RCTConvert BOOL: json];
}
RCT_CUSTOM_VIEW_PROPERTY(userAgent, NSString, RNCWebView) {
view.userAgent = [RCTConvert NSString: json];
}
RCT_CUSTOM_VIEW_PROPERTY(scrollEnabled, BOOL, RNCWebView) {
view.scrollEnabled = json == nil ? true : [RCTConvert BOOL: json];
}