How To Call JavaScript From Blazor Web Assembly - Breaking Boundaries with JavaScript Interop

Blazor is a technology that allows developers to create web applications using C# and .NET instead of traditional client-side JavaScript. With Blazor, developers can build interactive web applications that run fully on the client-side without relying on server-side rendering. This can lead to a smoother user experience and improved performance. However, using Blazor doesn't necessarily mean that developers should abandon JavaScript entirely. In fact, Blazor supports JavaScript Interop, which allows developers to call JavaScript functions from C# and vice versa. In this article, we'll dive into how to call JavaScript from Blazor Web Assembly using JavaScript Interop and provide examples of how this can be done. Whether you're new to Blazor or simply want to push its capabilities further, this article will have something for you.


Background on Blazor and JavaScript Interop

Blazor is a web framework built on .NET that allows developers to build client-side web applications using C#. In other words, it allows developers to use C# to create interactive client-side experiences. One important concept in Blazor is JavaScript Interop.

JavaScript Interop is a feature of Blazor that allows developers to call JavaScript functions from C# and vice versa. This feature is very important because it enables developers to use third-party JavaScript libraries and APIs with Blazor. This is important because, as much as Blazor is a powerful web development framework, it doesn't provide the same level of functionality as some popular JavaScript libraries.


Where Does JavaScript Go?

Blazor WebAssembly is a pretty cool tool for web developers, allowing you to build interactive web UIs using C# instead of JavaScript. But let’s face it, sometimes we still need a bit of JavaScript to get things done. So, where can you place JavaScript when working with Blazor WebAssembly?

If we check out the Microsoft documentation for this, they call out this important note related to their examples in the documentation:

Documentation examples usually place scripts in a <script> tag or load global scripts from external files. These approaches pollute the client with global functions. For production apps, we recommend placing JavaScript into separate JavaScript modules that can be imported when needed. For more information, see the JavaScript isolation in JavaScript modules section.

learn.microsoft.com

Let’s dive in and explore the options Microsoft recommends!

Load a Script in <head> Markup

First up, you might be tempted to load a script in the <head> markup

<head>
    ...

    <script>
      window.jsMethod = (methodParameter) => {
        ...
      };
    </script>
</head>

It seems straightforward, but Microsoft gives this method a thumbs down for general use. Why?

  • The interop with JavaScript might fail if the script depends on Blazor. Microsoft recommends loading scripts using other approaches and not using the <head> markup.
  • The page may become interactive slower due to the time it takes to parse the JS in the script.

It’s like waiting for your coffee to brew – it’s worth it for the caffeine, but you wish it could be instant! I know I sure wish caffeine was instant...

Load a Script in <body> Markup

Next, we have the option to load a script in the <body> markup.

<body>
    ...

    <script src="{BLAZOR SCRIPT}"></script>
    <script>
      window.jsMethod = (methodParameter) => {
        ...
      };
    </script>
</body>

This method is more in the good graces of Microsoft. Placing your script here means it won’t block the rendering of the page, so your users won’t be left waiting. It’s like grabbing a ready-made coffee – quick and convenient!

Load a Script from an External JavaScript File (.js) Collocated with a Component

Getting a bit more specific, you can load a script from an external JavaScript file that’s collocated with a component. This method is like having a coffee machine right next to your desk – super handy! It allows you to keep related scripts and components together, making your codebase more organized and manageable.

The Blazor example they mention in their documentation explains that you would have:

  • YourPage.razor
  • YourPage.razor.js

And these two files would be located side by side. In the OnAfterRenderAsync method of your razor page, you would call the following:

module = await JS.InvokeAsync<IJSObjectReference>(
    "import", "./Components/Pages/YourPage.razor.js");

Another important note is that the framework will automatically move the script to the web root when the app is published.

Load a Script from an External JavaScript File (.js)

Alternatively, you can load a script from any external JavaScript file (.js). This method is flexible and lets you keep your JavaScript files wherever you want in your project. It’s like having a coffee shop on every corner – you’re never far from what you need! Is the caffeine dependency shining through in this article?

I do recommend you read through Microsoft's specifics here so that you understand how the paths work. They call out specifics for Razor class libraries as well which will be helpful to understand.


Calling JavaScript from Blazor Using JavaScript Interop

Blazor and JavaScript can work together like coffee and cream (or milk!), thanks to JavaScript Interop! JavaScript Interop allows Blazor to execute JavaScript functions from .NET methods and vice versa. So, how do you call JavaScript from Blazor?

Let’s brew some code and find out!

Injecting IJSRuntime

First things first, you need to inject IJSRuntime into your component. IJSRuntime is the service that provides the magic to call JavaScript functions from Blazor. Here’s how you inject it:

@inject IJSRuntime JSRuntime

This step is going to be critical for making the rest of the tutorial work.

Writing JavaScript Function

Next, let’s write a simple JavaScript function. You can place this function in your index.html file inside the <script> tag or in an external JavaScript file. And where else can we place it? Well, scroll back up and you can read all of the different options you have!

Here’s an example of a function that shows an alert:

function showAlert(message) {
    alert(message);
}

Calling JavaScript Function from Blazor

Now, back in your Blazor component, you can call this JavaScript function using the InvokeVoidAsync method if the function doesn’t return a value, or InvokeAsync if it does. Here’s how you can call the showAlert function:

@code {
    private async Task CallJavaScriptFunction()
    {
        await JSRuntime.InvokeVoidAsync("showAlert", "Dev Leader says, 'Hello!', from Blazor!");
    }
}

In this example, "showAlert" is the name of the JavaScript function you want to call, and "Dev Leader says, 'Hello!', from Blazor!" is the parameter you’re passing to the function.

Triggering the Call

Finally, you can trigger this call from a UI event like a button click. Here’s how you can do it:

<button @onclick="CallJavaScriptFunction">Show Alert</button>

When you click the button, it will call the CallJavaScriptFunction method, which in turn calls the showAlert JavaScript function, and you’ll see an alert with the message "Dev Leader says, 'Hello!', from Blazor!"


Keep These in Mind When You Call JavaScript From Blazor Web Assembly...

Blazor Web Assembly's JavaScript Interop is a powerful tool, but it does come with certain limitations and considerations. One potential drawback of using this feature is the risk of reduced performance. When calling JavaScript from C#, there is a risk of slow execution times. As a result, it's important that you're aware of this and not over-using it for performance-sensitive situations.

To use JavaScript Interop successfully, it is highly recommended to follow best practices. One of the best practices is to avoid using the Interop for performance-critical sections of the code. Additionally, it's recommended to ensure that both the JavaScript and C# code are optimized. Testing and debugging are incredibly important in ensuring the smooth and stable functioning of Blazor Web Assembly with JavaScript Interop. It is also important to make sure that JavaScript code is properly tested and debugged to reduce the risk of any compatibility issues.

By being mindful of these considerations, software engineers can make the most of the JavaScript Interop in Blazor Web Assembly without sacrificing performance or stability.


And Now You Know How To Call JavaScript From Blazor Web Assembly!

Calling JavaScript from Blazor Web Assembly is a powerful technique for enhancing web functionality. With the help of JavaScript Interop, developers can easily integrate JavaScript libraries and frameworks with Blazor. And as for the coffee analogies? I don't even drink coffee - shocking right? I do love my caffeine though.

We covered the key concepts of Blazor and JavaScript Interop and explained how to enable JavaScript Interop and call JavaScript from Blazor using an example we could walk through. However, it is important also to consider the limitations and best practices for using JavaScript Interop to avoid potential performance issues.

I definitely encourage you to experiment with JavaScript Interop in Blazor and explore the possibilities of web development with Blazor Web Assembly. Don't forget to subscribe to Dev Leader Weekly and my YouTube channel for more tips and resources on software engineering and C#!

Affiliations

These are products & services that I trust, use, and love. I get a kickback if you decide to use my links. There’s no pressure, but I only promote things that I like to use!

  • BrandGhost: My social media content and scheduling tool that I use for ALL of my content!
  • RackNerd: Cheap VPS hosting options that I love for low-resource usage!
  • Contabo: Affordable VPS hosting options!
  • ConvertKit: The platform I use for my newsletter!
  • SparkLoop: Helps add value to my newsletter!
  • Opus Clip: Tool for creating short-form videos!
  • Newegg: For all sorts of computer components!
  • Bulk Supplements: Huge selection of health supplements!
  • Quora: I answer questions when folks request them!

Plugin Architecture in Blazor - A How To Guide

Like building ASP.NET web applications and want to maximize extensibility? This guide is a how-to on using a plugin architecture in Blazor. Check it out!

Build a Blazor Web App Series - Get In The Know

Welcome to the Build a Blazor Web App Series! This is an exclusive Dev Leader Weekly article.

What Are The Easiest Programming Languages to Learn? - Your Ultimate Guide

Discover the easiest programming languages to learn in this beginner-friendly guide. From Python to JavaScript, let's see what options we have to work with!

An error has occurred. This application may no longer respond until reloaded. Reload x