Search code examples
delphibrowsertms-web-core

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


I'd like to know what browser (Microsoft Edge, Google Chrome, Mozilla Firefox, Opera, Safari, etc.) the user has on his computer.

It would be nice if I could also see what version of the browser the user has.

How can I check or get the browser name and/or browser version with Delphi?


Solution

  • You can get the browser name and version from window.navigator.userAgentData.brands, but this isn't natively implemented in TMS Web Core yet. window.navigator.userAgentData.brands also isn't implemented in all the browsers yet.

    But here's an answer using window.navigator.userAgentData.brands and then window.navigator.userAgent as a fallback in case the browser doesn't support the first method:

    uses Web;
    
    ...
    
    function GetBrowser(IncludeVersion: Boolean): String;
    var
      UserAgent: String;
    begin
      Result := '';
      asm
        const userAgentData = window?.navigator?.userAgentData?.brands;
        if (userAgentData !== undefined) {
          Result = `${userAgentData[0].brand}`;
          if (IncludeVersion === true)
            Result = `${Result} (${userAgentData[0].version})`;
        }
      end;
      if (Result = '') then
      begin // Fallback in case browser doesn't have "userAgentData.brands"
        UserAgent := window.navigator.userAgent;
        Result := 'Unknown Browser';
        if (UserAgent.indexOf('Firefox') <> -1) then Result := 'Mozilla Firefox'
        else if (UserAgent.indexOf('Safari') <> -1) then Result := 'Safari'
        else if (UserAgent.indexOf('Trident') <> -1) then Result := 'Internet Explorer'
        else if (UserAgent.indexOf('Edg') <> -1) then Result := 'Microsoft Edge'
        else if (UserAgent.indexOf('Chrome') <> -1) then Result := 'Google Chrome'
        else if (UserAgent.indexOf('Vivaldi') <> -1) then Result := 'Vivaldi'
        else if (UserAgent.indexOf('YaBrowser') <> -1) then Result := 'Yandex Browser'
        else if (UserAgent.indexOf('OPR') <> -1) then Result := 'Opera';
    
        if (IncludeVersion = true) then
          Result := Result + ' (Unknown Version)';
      end;
    end;