我想修改 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/