Reputation: 1746
I need to detect if the user of my blazor server side application is using a mobile device. Is there any way to find out which device the user is using?
I know I can do it with a JSRuntime but is there any way to figure it out with pure C#?
Upvotes: 8
Views: 11104
Reputation: 84
In Blazor Server (SSR) the best way I found is by accessing the HttpContext.
First we inject the httpContext
@inject IHttpContextAccessor httpContextAccessor
and then we can check in OnInitializedAsync
var userAgent = httpContextAccessor?.HttpContext?.Request.Headers["User-Agent"].ToString();
if (userAgent != null && (userAgent.Contains("Android") || userAgent.Contains("iPhone")))
{
IsMobile = true;
}
I hope it helps!
Upvotes: 0
Reputation: 968
Same answer as Chris, but here is the link to the article where the code is from:
Syncfusion mobile detection article
Included on this page is also a link to a site where this method has been implemented to help you test if this works for your specific use case and device:
Upvotes: 2
Reputation: 148
You can detect the user agent on the JavaScript side of your app, and reference that from the C# side.
Keep in mind that iPad browsers have some mobile features and some desktop features, so it is up to you how you want to handle iPad.
Here is a script taken from the Sycfusion website:
[wwwroot/script.js]
function isDevice() {
return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(navigator.userAgent);
}
To include it in your app, you reference it in index.html
[index.html/_Host.cshtml]
<head>
.....
<script src="~/script.js"></script>
....
</head>
and then you invoke it in you blazor code
[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";
}
}
Upvotes: 7
Reputation: 176
I did find this article that will read you the width and height of a window in Blazor. Looks like it uses JS Interop. With that, you can determine if a user is using a mobile based on the width of their resolution. Of course, it's not 100% full proof as someone on a desktop can resize their window down to a mobile resolution. https://blazor.tips/blazor-how-to-ready-window-dimensions/
Upvotes: 4