如何在 blazor 服务器端应用程序中检测移动设备?

Mar*_*ein 8 c# asp.net-core blazor blazor-server-side

我需要检测 blazor 服务器端应用程序的用户是否正在使用移动设备。有什么办法可以查出用户正在使用哪个设备?

我知道我可以使用 JSRuntime 来完成,但是有什么方法可以使用纯 C# 来解决这个问题吗?

小智 6

您可以在应用程序的 JavaScript 端检测用户代理,并从 C# 端引用它。

请记住,iPad 浏览器具有一些移动功能和一些桌面功能,因此这取决于您想要如何处理 iPad。

以下是来自 Sycfusion 网站的脚本:

    [wwwroot/script.js]

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

要将其包含在您的应用程序中,您可以在index.html中引用它

[index.html/_Host.cshtml]

<head>
 .....
 <script src="~/script.js"></script>
 ....
</head>
Run Code Online (Sandbox Code Playgroud)

然后在 blazor 代码中调用它

[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";

    }
}
Run Code Online (Sandbox Code Playgroud)


小智 3

我确实找到了这篇文章,它将向您展示 Blazor 中窗口的宽度和高度。看起来它使用了 JS Interop。这样,您就可以根据用户的分辨率宽度来确定用户是否正在使用移动设备。当然,这并不是 100% 完全证明,因为桌面上的用户可以将窗口大小调整为移动分辨率。 https://blazor.tips/blazor-how-to-ready-window-dimensions/