Search code examples
blazorblazor-hybrid

How to find app's platform within a Razor class library?


I'm making an app that uses both Blazor Hybrid and Blazor Server projects with one set of Razor UI components shared across the different platforms. Most of the UI components, including the main layout, are in a separate Razor class library project. The main layout references components that compose the navigation bar.

I want to display different navigation bar components for desktop and mobile platforms.

So how can I find what platform the app is running on? An alternative solution I thought could be to use bootstrap and display a different component based on the size of the page. This would not be enough because if a page on a tablet is big enough, the navigation will revert to a style that's meant for a desktop application. However, I will be using this method to make adjustments for the browser platform.


Solution

  • I suggest the following approach:

    1. Prepare a JavaScript function that returns true if it detects that the app is on a mobile device:
    function isMobileDevice() {
        if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
            return true;
        }
    
        return false;
    }
    

    You will need to paste it in a JavaScript file in your /wwwroot folder. For example, in a "js" folder, with the file name "device.js".

    1. Insert <script src="js/device.js"></script> script tag into your index.html.

    2. In your component, create a OnInitialize method and in it call InvokeAsync method from an instance of JSRuntime:

            [Inject] IJSRuntime? JSRuntime { get; set; }
            public bool IsMobile { get; set; }
    
            protected override async Task OnInitializedAsync()
            {
                if (JSRuntime is null) return;
    
                IsMobile = await JSRuntime.InvokeAsync<bool>("isMobileDevice");
            }
    
    1. Use the IsMobile field in your Razor template to determine which navbar to display.