1

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?

1 Answer 1

1

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

jsModule.InvokeVoidAsync("showAlert", "hello");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.