How to use JavaScript in Blazor

How to use JavaScript in Blazor

Blazor is able to work in the browser because WebAssembly has been enabled in the browser in 2019 as the fourth programming language beside HTML, CSS and JavaScript. This had lead to that we can now use C# instead of JavaScript. However there is still in some cases you might want to use JavaScript anyway, by using JS Interops.

10-11-2022 |

ASP.NET Core
.NET
Blazor
JavaScript

You can have many reasons to actually use JavaScript even though we can use C# for most of what JavaScript is providing. However if you want to use a library with effects like jQuery, then you want to use JS Interops.

The name JS Interops comes from JavaScript interoperability, where interoperability is the ability for two things to work together. In this case it is JavaScript and .NET that is working together. Because you can actually call .NET method by using JS but also use JS to call .NET methods.

To call a JavaScript function using .NET I have in this case used a Blazor Server App project. The only two files we have to edit is the _Host.cshtml file and the file we want to make the JavaScript happen. In my case it is just the frontpage of the Blazor Server App template.

The JS script tag should in a Blazor Server App always be placed in the _Host.cshtml file, otherwise the script tag won’t work. In this case I just added a function called showAlert which takes one parameter which is the message that should be shown in the alert box. The function will create a new paragraph element by using only JS and add it to the div that have an id of p-container.

Execute from .NET to trigger JavaScript in a Blazor Server App

_Host.cshtml
Index.razor

Remember to inject IJSRuntime in the .razor file and when using InvokeAsync remember to do the function async as well.


Like what you see?


New C# Learning Area - Free!

Our website now offers a new section on C# theory, including code examples and related video tutorials.

ZetBit

Subscribe to ZetBits Newsletter