Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

Unable to invoke javascript function from blazor component

$
0
0

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

Please check this image as well.

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, orproperty 'JSRuntime.InvokeAsync(string, object[])'

second error


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>