In this post, we are going to see how to run JavaScript from our .NET code in Blazor, and how to execute .NET code from JavaScript, for this we'll use JavaScript interop.
Table of Contents
1 - Why run JavaScript in Blazor
First of all, we need to understand why we need to run JavaScript in our Blazor applications.
As we know, when we build applications in Blazor, what Blazor uses behind the scenes to communicate with the user through the browser is JavaScript.
The language's architecture is like the following: the blazor ( c# + razor)
application is executed by the .NET Runtime
which in the web assembly version talks directly to the JavaScript runtime.
Whereas in the server-side version, it does it using SignalR
.
By default, Blazor brings most of the “regular” JavaScript actions already implemented – for example, the onclick of a button. Unfortunately, Blazor does not provide access to the entire browser API, for example, we don't have access to the DOM, location, LocalStorage, or the navigation history.
But it doesn't end there. A large part of the web nowadays is written in JavaScript, and many third-party libraries (like the one containing the code inside my posts) are available only in JavaScript, so to make them work, we must be able to run custom JavaScript from our Blazor app.
- Note: We will be able to access this both in the
WebAssembly
version and theserver-side
version.
2 - How to run JavaScript from Blazor
The first thing we'll do for this example is to create a JavaScript file inside our wwwroot folder, which we need to reference from our index.html
if we're using WebAssembly or _host.cshtml
if server-side
<script src="js/script.js"></script>
Now, we need to create the JavaScript function we want to call, for this we must declare it in the global scope.
If you're using Visual Studio, when you open the file you can see at the top which scope you're in.
So, let's create a function that simply shows an alert.
window.MostrarAlerta = function(message) {
alert(message);
}
- Note: in real world cases, you would execute your complete functionality.
2.1 - Call a JavaScript function from Blazor
Now we just have to call our function from C#. For that, go to the component where you want to call the function and inject the type IJSRuntime
, which allows us to execute JavaScript from Blazor.
@inject IJSRuntime jsRuntime
And create a method in our component that we'll call from a button, and using the InvokeVoidAsync
method of IJSRuntime
, we call the JavaScript function.
@inject IJSRuntime jsRuntime
<button @onclick="EjecutarJs">Ejecutar JavaScript</button>
@code{
public void EjecutarJs()
{
jsRuntime.InvokeVoidAsync("MostrarAlerta", "Mensaje enviado desde c# a Js");
}
}
As we can see, the first parameter is the function name and the second uses the param keyword, which allows us to send as many as we want (param object[] args
).
If we wanted to receive a value from the function, we'd need to call InvokeAsync
, which returns ValueTask<T>
where T
is the return type. Of course, for that, you should use await and do the async code.
If you click the button, you will see the result
- Note: The same way we invoked alert in our JS function, you could invoke localstorage or any other browser API.
3 - How to execute C# code from JavaScript
Just like we call a JS function from Blazor, we can do the reverse, calling a class written in C# from JavaScript.
First, we need to create a static method in C#, and decorate it with the [JSInvokable]
attribute which will allow it to be called from JavaScript.
To test the method, we can call it directly from the browser using the developer tools. In the console, call window.DotNet.InvokeMethodAsync, passing a few parameters: the assembly name, the method name, and any parameters the method is going to receive.
window.DotNet.invokeMethod("WebPersonal.FrontEnd.WebApp","GetNombreCompleto", "NetMentor");
//Respuesta de la consola de javascrpt
"el nombre es NetMentor"
- Note: if you use
invokeMethodAsync
you will receive a JavaScriptpromise
.
3.1 - Call a C# method from JavaScript
To call the method “automatically” on our web page, unfortunately you need to use the same code, but this time put it inside a function in your script.js file
window.LlamarCSharp = function () {
var result = window.DotNet.invokeMethod("WebPersonal.FrontEnd.WebApp",
"GetNombreCompleto", "NetMentor");
alert(result);
}
Now from any part of the code you can create handlers or call this function, in this example I'll use a button.
<button onclick="window.LlamarCSharp()">Llamar C# desde JS</button>
And if you run it you can see the result:
Conclusion
- In this post, we've seen why it's important to call JavaScript from Blazor, as this allows us to access the full browser API.
- We've covered how to call JavaScript functions from .NET.
- We've covered how to invoke methods in .NET from JavaScript.
If there is any problem you can add a comment bellow or contact me in the website's contact form