Search code examples
c#blazorblazor-webassembly

calling a JS function for use in razor component code file


I am attempting to use some JS code in my blazor client side components, I have followed some examples online but cannot get it to work.

Component.razor.cs

namespace MyApp.Web.Components.Select
{
    public partial class Select
    {
        [Parameter]
        public RenderFragment ChildContent { get; set; } = default!;

        [Inject]
        public IJSRuntime JSRuntime { get; set; }

        private IJSObjectReference jsModule;

 
        public void OnClick()
        {
            ShowAlertWindow();
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            try
            {
                jsModule = await JSRuntime.InvokeAsync<IJSObjectReference>("import", "./scripts/test.js");
            }
            catch (Exception ex)
            {
                System.Console.WriteLine($"Failed to load JS module. Error: {ex}");
            }
        }

        public void ShowAlertWindow()
        {
            System.Console.WrteLine("Showing Alert Window");   // this works
            JSRuntime.InvokeVoidAsync("showAlert", "hello");   // this does nothing
        }
    }
}

Component.razor

<div class="wrapper">
    <div @onclick="@OnClick">
        @ChildContent
    </div>
</div>

wwwroot/scripts/test.js

export function showAlert(message) {
    alert(message);
}

At run time, the click should run the custom showAlert function in the JS file. but nothing seems to happen, no errors in browser dev console neither.

What I am doing wrong?


Solution

  • You have to use the IJSObjectReference that you obtained inside OnAfterRenderAsync to invoke the showAlert function:

    jsModule.InvokeVoidAsync("showAlert", "hello");