How To Call JavaScript From Blazor Web Assembly – Breaking Boundaries With JavaScript Interop

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.

Sign up for Dev Leader Weekly!

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.

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

      window.jsMethod = (methodParameter) => {

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.

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

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) {

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…

If you’ve enjoyed this article excerpt so far, you can read about some additional considerations with JavaScript and Blazor interop in the full article. My newsletter readers get a list of all of my full-length articles and my full-length videos sent to their email every weekend. They also periodically get exclusive newsletter articles and potential early access to my full-length videos. All for free! Consider signing up to Dev Leader Weekly to keep up to date!

Sign up for Dev Leader Weekly!

Did you find this article valuable?

Support Dev Leader by becoming a sponsor. Any amount is appreciated!