I'm trying to check if my blazor web assembly app is opened on mobile or not. For that,
I created a wwwroot/script.js file and added code:
function isDevice() {
return /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile/i.test(navigator.userAgent);
}
Added reference in index.html
And then in my component:
@inject IJSRuntime JSRunTime
@code {
private string isDevice { get; set; }
private static bool mobile { get; set; }
protected async override Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
mobile = await JSRuntime.InvokeAsync<bool>("isDevice");
isDevice = mobile ? "Mobile" : "Desktop";
}
await base.OnAfterRenderAsync(firstRender);
}
}
I'm getting an error on compile time that:
No overload for method 'InvokeAsync' takes 1 arguments
After checking the docs: https://learn.microsoft.com/en-us/dotnet/api/microsoft.jsinterop.jsruntime.invokeasync?view=aspnetcore-5.0#Microsoft_JSInterop_JSRuntime_InvokeAsync__1_System_String_System_Object___
I changed the code to have second parameter like this:
mobile = await JSRuntime.InvokeAsync<bool>("isDevice", new object[] { });
Now the error is:
An object reference is required for the non-static field, method, or property 'JSRuntime.InvokeAsync(string, object[])'
JSRuntime.InvokeAsync<bool>("isDevice", new object[] { });
but now the error is: An object reference is required for the non-static field, method, or property 'JSRuntime.InvokeAsync<bool>(string, object[])' – Pigment