Obr*_*ios 8 android ios react-native
我想修改WebView中的用户代理字符串,以便在服务器端我可以检测到请求来自我的react-native应用程序.我想使用WebView中的source prop来做到这一点.
我如何为IOS和Android执行此操作?
van*_*ren 12
您可以将其设置为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];
Run Code Online (Sandbox Code Playgroud)
在Android上(我在我的WebView中设置了JS中的userAgent):
<WebView
userAgent={DeviceInfo.getUserAgent() + " - MYAPPNAME - android "}
ref={"WEBVIEW"}
automaticallyAdjustContentInsets={false}
source={{uri: this.state.url}} />
Run Code Online (Sandbox Code Playgroud)
现在我总是有一个像"DeviceInfo - MYAPPNAME - Platform"这样的userAgent.我们像你一样做同样的事情,它的工作方式如何.
对于Android,您只需要设置userAgent属性,例如:
<WebView
source={{ uri: "https://stackoverflow.com" }}
userAgent="Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
/>
Run Code Online (Sandbox Code Playgroud)
对于iOS,在实现中需要在方法内部didFinishLaunchingWithOptions(行前return YES;)添加如下代码AppDelegate.m:
NSString *userAgent = @"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36";
NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:userAgent, @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9900 次 |
| 最近记录: |