Live Chat Icon For mobile
Live Chat Icon

How do you detect whether a page is loaded in mobile or on desktop?

There is no direct way to detect whether the page is loaded on mobile or desktop in Blazor. We have to find out through the userAgent property from the JavaScript side using a JSInterop call. In order to find out, add a “script.js” file in the wwwroot folder and include the isDevice method call. You can then invoke the isDevice method to identify the correct device.

Refer to the following code for further details.

[wwwroot/script.js]

function isDevice() {
    return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(navigator.userAgent);
}

Refer the script file in the HTML page

[index.html/_Host.cshtml]

<head>
 .....
 <script src="~/script.js"></script>
 ....
</head>
[index.razor]

@page "/"
@inject IJSRuntime jsRuntime

<h1>Responsive</h1>

<button @onclick="FindResponsiveness">Find Device</button>
<h2>@isDevice</h2>
@code {
    private string isDevice { get; set; }
    private bool mobile { get; set; }
    public async Task FindResponsiveness()
    {
        mobile = await jsRuntime.InvokeAsync<bool>("isDevice");
        isDevice = mobile ? "Mobile" : "Desktop";

    }
}

For more details about mobile browser detection, refer to this link.

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.