DEV Community

starpebble
starpebble

Posted on

Identifying the OS version and phone model hosting a React Native mobile app purely with JavaScript

When it is absolutely necessary to determine the OS and phone model in a React Native app it can be done with purely with JavaScript. Please let me explain how exactly the open source React Native component info-glass does it.

User Agent String

The React Native WebView component can execute a simple JavaScript function that returns the user agent string. That means the WebView will kinda reply like a web browser does.

The user agent string identifies the mobile app's host:

  1. OS name
  2. OS version
  3. Phone model

It doesn't have to be a phone the WebView can also identify a mobile device model like a tablet too.

Code

<script>
  function getinfo() {
    if(window.postMessage.length !== 1) {
      setTimeout(getinfo, ${ASYNCHRONOUS_DELAY_MS});
    } else {
      window.postMessage(window.navigator.userAgent);
    }
  }
  window.onload = getinfo;
</script>

The code snippet above is just a single javascript function named getinfo() in a single HTML script tag. The function getinfo() returns the window.navigator.userAgent string for the WebView.

The secret is that a WebView component instance can send a message to the containing React Native component through the JavaScript function window.postMessage().

info-glass

The npm package info-glass is a single JavaScript component that does one or two more things to simplify the above snippet. The source code is on Github in one single index.js file.

Every single React Native project is different. I simply like building purely in JavaScript because:

  1. Developer operation simplifications.
  2. Debugging a purely JavaScript application is relatively easy.
  3. Dust bunnies are easy to find with a JavaScript linter.

It's not too difficult to mix in native code, it simply isn't always absolutely necessary to write native code. If you are trying to be a humble JavaScript champion, it can't hurt to use a WebView to get the userAgent.

Top comments (0)