I’m looking to get the user agent string from a mobile device to use in Google Analytics. Is there any way within the Expo environment to easily retrieve this string? I want to avoid using ExpoKit and adding specific OS dependencies. Is there a method via Expo (or React Native in general) that I haven’t seen that provides me the device’s user agent?
We don’t have a great way of accessing this right now but I’ll add it to our list.
For now a really hacky way to do this is use an invisible webview and use https://facebook.github.io/react-native/docs/webview.html#onmessage to send the user agent back to your app. I made an example of this technique here: https://snack.expo.io/r1Xun_7eb
Thanks for the help Jesse. I appreciate the quick response. I’ll try your suggestions.
It looks like there is a bug in snack that breaks that specific page. Let me know if you need help figuring it out.
Will do. Thanks for the assistance. It looks pretty straight forward (for a convoluted workaround ).
As you said, the snack page isn’t displaying your code. Can you post your example code in here? I think it might help me. Much appreciated.
Just fixed the snack link so it should work now!
That looks like just what I need. Thanks for the help. It probably would have taken me a while to get to the code you have (somewhat new to React/React Native/JS, etc.). Thanks so much!
@jesse
Could you help me understand how I could use this to implement Google Analytics?
I’m using react-native-google-analytics which requires a userAgent.
What don’t you understand about it? Looks like you’d just use the code I posted above instead of DeviceInfo.getUserAgent()
here GitHub - rnc-archive/react-native-google-analytics: Google Analytics for React Native! Compatible with react-native-ab
FYI I went down this path (trying the WebView thing) and later found this: https://docs.expo.io/versions/latest/sdk/constants.html#expoconstantsgetwebviewuseragentasync which returns a Promise so you can use it like this:
Expo.Constants.getWebViewUserAgentAsync()
.then(agent => console.log('User agent:', agent))