Why Use JavaScript?

Learn why we need to use JavaScript with Blazor.

Why use JavaScript?

With Blazor WebAssembly, we can create complete applications without directly using JavaScript. However, we may need to use JavaScript because there are some scenarios that we cannot accomplish without it. Without JavaScript, we can’t manipulate the DOM or call any of the JavaScript APIs that we rely on for web development.

This is a sample of the things that we do not have access to directly from the Blazor WebAssembly framework:

  • DOM manipulation
  • The Media Capture and Streams API
  • The WebGL API (2D and 3D graphics for the web)
  • The Web Storage API (localStorage and sessionStorage)
  • The Geolocation API
  • JavaScript pop-up boxes (alert, confirm, prompt)
  • The online status of the browser
  • The browser’s history
  • Chart.js
  • Other third-party JavaScript libraries

The preceding list is not at all comprehensive since there are hundreds of JavaScript libraries that are currently available. However, the key point to remember is that we cannot manipulate the DOM without using JavaScript. Therefore, we will probably always need to use some JavaScript in our web apps. Luckily, by using JS interop, this is easy to do.

Exploring JS interop

To invoke a JavaScript function from .NET, we use the IJSRuntime abstraction. This abstraction represents an instance of a JavaScript runtime that the framework can call into. To use IJSRuntime, we must first inject it into our component using dependency injection. The @inject directive is used to inject a dependency into a component. The following code injects IJSRuntime into the current component:

Get hands-on with 1200+ tech skills courses.