使用带有react-native的WebView设置用户代理 [英] Set user agent with WebView with react-native

查看:83
本文介绍了使用带有react-native的WebView设置用户代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WebView中修改用户代理字符串,以便在服务器端可以检测到该请求来自我的本机应用程序.我想使用WebView中的源道具来做到这一点.

I want to modify the user agent string in a WebView so that on the server side I can detect that the request has come from my react-native app. I want to do this using the source prop in the WebView.

如何针对IOS和Android执行此操作?

How do I do this for IOS and Android?

推荐答案

您只需将其设置为WebView中的道具即可.

You just can set it as a prop in your WebView.

我正在执行以下操作:

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

on iOS (I set the userAgent in AppDelegate.m)

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)

on Android (I set the userAgent in JS in my WebView):

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

现在我一直都有一个userAgent,例如"DeviceInfo-MYAPPNAME-Platform".我们和您一样在做同样的事情,并且按预期的方式运作.

now I'm always having a userAgent like "DeviceInfo - MYAPPNAME - Platform". We're doing the same like you and it works how it's supposed to do.

这篇关于使用带有react-native的WebView设置用户代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆