Calling JavaScript from .NET in Blazor

JavaScript should be added into either /Pages/_Host.cshtml in Server-side Blazor apps, or in wwwroot/index.html for Web Assembly Blazor apps.

BlazorApp.js

var BlazorApp = {
    helloWorld: function () {
        alert("Hello World");
    },
    hello: function (name) {
        alert("Hello " + name);
    },
    sayHi: function (name) {
        return "Hello " + name;
    }
};

add to _Host.cshtml :

<script src="~/scripts/BlazorApp.js"></script>

Index.razor

@page "/"
@inject IJSRuntime JsRuntime;

<div>
    Name : <input @bind-value="name"/>
</div>

<button @onclick="Hello">Hello</button>
<button @onclick="SayHi">Say Hi</button>

<p>@output</p>

@code
{
    private string name;
    private string output;

    protected override Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
    // here blazor is ready to call javascript
            Console.WriteLine("Javascript is ready");
            JsRuntime.InvokeVoidAsync("BlazorApp.helloWorld");
        }

        return base.OnAfterRenderAsync(firstRender);
    }

    private async Task Hello()
    {
        await JsRuntime.InvokeVoidAsync("BlazorApp.hello", name);
    }

    private async Task SayHi()
    {
        output = await JsRuntime.InvokeAsync<string>("BlazorApp.sayHi", name);
    }
}

References
https://blazor-university.com/javascript-interop/calling-javascript-from-dotnet/
https://blazor-university.com/javascript-interop/calling-javascript-from-dotnet/updating-the-document-title/