Need User Agent String

#1

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?

2 Likes

#2

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

1 Like

#3

Thanks for the help Jesse. I appreciate the quick response. I’ll try your suggestions.

0 Likes

#4

It looks like there is a bug in snack that breaks that specific page. Let me know if you need help figuring it out.

0 Likes

#5

Will do. Thanks for the assistance. It looks pretty straight forward (for a convoluted workaround :blush:).

0 Likes

#6

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.

0 Likes

#7

Just fixed the snack link so it should work now!

0 Likes

#8

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!

1 Like

#9

@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.

0 Likes

#10

What don’t you understand about it? Looks like you’d just use the code I posted above instead of DeviceInfo.getUserAgent() here https://github.com/lwansbrough/react-native-google-analytics#usage

0 Likes

#11

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))
2 Likes