android - 使用带有 react-native 的 WebView 设置用户代理

标签 android ios react-native

我想修改 WebView 中的用户代理字符串,以便在服务器端我可以检测到请求来 self 的 react-native 应用程序。我想在 WebView 中使用 source prop 来做到这一点。

如何为 IOS 和 Android 执行此操作?

最佳答案

您只需将其设置为 WebView 中的 Prop 即可。

我正在做以下事情:

在 iOS 上(我在 AppDelegate.m 中设置了 userAgent)

NSString *deviceType = [UIDevice currentDevice].model;
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSString *newAgent = [oldAgent stringByAppendingString:@" MYAPPNAME - iOS - "];
newAgent = [newAgent stringByAppendingString:deviceType];
NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];

在 Android 上(我在 WebView 的 JS 中设置了 userAgent):

<WebView
    userAgent={DeviceInfo.getUserAgent() + " - MYAPPNAME - android "}   
    ref={"WEBVIEW"}
    automaticallyAdjustContentInsets={false}
    source={{uri: this.state.url}} />

现在我总是有一个像“DeviceInfo - MYAPPNAME - Platform”这样的 userAgent。我们正在做和您一样的事情,它按照预期的方式工作。

关于android - 使用带有 react-native 的 WebView 设置用户代理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36590207/

相关文章:

Android Studio AdMob 错误无法解析符号 @integer/google_play_services_version"/>

ios - 核心数据: Inherited entities

react-native - 自定义字体不适用于 React-Native 0.62

javascript - 将数组作为属性传递

javascript - native react : react-navigation crashes when navigating with headerRight

android - 向 Realm 添加新字段后如何设置默认值?

android - android中用户点击后退按钮时如何保存进度条的进度状态

android - WebViewClient.shouldOverrideUrlLoading 给出无效的 url

ios - 导航栏后退按钮未显示?

ios - 在 MacCatalyst 的 SwiftUI 应用程序中隐藏标题栏