DEV Community

Cover image for How To Call JavaScript From Blazor Web Assembly – Breaking Boundaries With JavaScript Interop
Dev Leader
Dev Leader

Posted on • Originally published at devleader.ca

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.

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>
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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!");
    }
}
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (2)

Collapse
 
kiss_code profile image
kis.stupid

Cool! I was about to write on this subject as well. That dynamic script importing is a game changer for me!

I like to work with a modular setup, so encapsulating scripts in Razor components is a requirement. I recently noticed, just putting the script tag on your component wasn't too reliable, so I fixed that using the dynamic script import method.

Collapse
 
devleader profile image
Dev Leader

Awesome :D Glad to hear it! I haven't had too many battles to fight yet, but I like exploring different options for things so when the time comes I feel prepared :)