Search code examples
androidreactjsreact-nativecross-platform

How to detect if my react native app was opened in a browser inside a phone


I want my app to react differently when opened in web depending on the machine.

For example, if the app runs on the web from a browser inside a phone it should display the screen in portrait mode, and if the app runs on the web from a computer it should display screen in landscape mode. And yes I know that in this specific case I could just use Dimentions API to measure the dimetions of the screen but this example is for illustration only to help you understand the problem.

I am familiar with the Platform.OS module in react native, and it indeed works great when the app runs from expo go or the web in windows - The problem starts when I try to detect the operating system where the web version of the app was opened from because then Platform.OS will always return "web" no matter if it was opened in android/ios/windows etc.


Solution

  • To detect both whether the app is running in a browser and determine the operating system (OS) using user agent .

    import { useEffect, useState } from 'react';
    import { Platform } from 'react-native';
    
    const useDetectEnvironment = () => {
      const [environment, setEnvironment] = useState({
        isInBrowser: false,
        os: null, // Possible values: "iOS", "Android", "Windows", "MacOS", "Linux", or "Unknown"
      });
    
      useEffect(() => {
        if (Platform.OS === 'web') {
          const userAgent = navigator.userAgent || navigator.vendor || window.opera;
    
          // Check if running in a browser
          const isInBrowser =
            /android/i.test(userAgent) ||
            /iPhone|iPad|iPod/i.test(userAgent) ||
            /Mobile|WebKit/i.test(userAgent);
    
          // Determine the OS based on the user agent
          let os = "Unknown";
          if (/android/i.test(userAgent)) {
            os = "Android";
          } else if (/iPhone|iPad|iPod/i.test(userAgent)) {
            os = "iOS";
          } else if (/Windows/i.test(userAgent)) {
            os = "Windows";
          } else if (/Macintosh|Mac OS X/i.test(userAgent)) {
            os = "MacOS";
          } else if (/Linux/i.test(userAgent)) {
            os = "Linux";
          }
    
          setEnvironment({ isInBrowser, os });
        } else {
          // For native platforms, use Platform.OS
          const os = Platform.OS === "android" ? "Android" : "iOS";
          setEnvironment({ isInBrowser: false, os });
        }
      }, []);
    
      return environment;
    };
    
    export default useDetectEnvironment;