Search code examples
delphioperating-systemtms-web-core

How do I get the user's Operating System in a TMS Web Core Website?


I'd like to know what operating system (Windows, MacOS, Linux, Android, iOS, etc.) the user has on his computer.

In FMX, I could simply do TOSVersion.ToString from System.SysUtils to get the operating system, but in TMS Web Core it doesn't work. I get the following error:

[Error] identifier not found "TOSVersion"

How can I check or get the operating system with Delphi in TMS Web Core?


Solution

  • You can use the following function:

    function GetOperatingSystem(): String;
    var
      UserAgent: String;
    begin
      UserAgent := window.navigator.userAgent;
      Result := 'Unknown';
      if (UserAgent.indexOf('Windows NT 10.0') <> -1) then Result := 'Windows 10'
      else if (UserAgent.indexOf('Windows NT 6.2') <> -1) then Result := 'Windows 8'
      else if (UserAgent.indexOf('Windows NT 6.1') <> -1) then Result := 'Windows 7'
      else if (UserAgent.indexOf('Windows NT 6.0') <> -1) then Result := 'Windows Vista'
      else if (UserAgent.indexOf('Windows NT 5.1') <> -1) then Result := 'Windows XP'
      else if (UserAgent.indexOf('Windows NT 5.0') <> -1) then Result := 'Windows 2000'
      else if (UserAgent.indexOf('Windows Phone') <> -1) then Result := 'Windows 10 Mobile'
      else if (UserAgent.indexOf('iPhone') <> -1) then Result := 'iOS'
      else if (UserAgent.indexOf('Mac') <> -1) then Result := 'MacOS'
      else if (UserAgent.indexOf('AppleTV') <> -1) then Result := 'tvOS'
      else if (UserAgent.indexOf('Android') <> -1) then Result := 'Android'
      else if (UserAgent.indexOf('Linux') <> -1) then Result := 'Linux'
      else if (UserAgent.indexOf('X11') <> -1) then Result := 'UNIX';
    end;
    

    But note that this isn't always 100% accurate. The userAgent can be changed by the browser or via code. It is also detecting Windows 11 as Windows 10.


    There is however a spec proposal that aims to help with the above issues: https://wicg.github.io/ua-client-hints/


    There is also this (detectOS.js) JavaScript library that you could possibly use for detecting the operating system.