Since Blazor runs on the browser, there are situations where we may need to execute a browser-native functionality. For that, there is no way to avoid JavaScript! There are two ways in which JavaScript and Blazor (.NET) can interoperate, as follows:
- .NET calls JavaScript functions.
- JavaScript calls .NET methods.
Calling JavaScript functions from .NET
Blazor can call any JavaScript function that is present on the hosting web page. It does this through the IJSRuntime object, which is automatically made available through the DI framework when you register Blazor.
For example, on the .razor file, add this code:
@inject IJSRuntime JSRuntime;
function add(a, b) { return a + b; }
@code
{
var result = await JSRuntime.InvokeAsync<int>("add", 1, 1);
}
IJSRuntime allows you to invoke any function by its name, passing an arbitrary number of parameters and receiving a strongly...