A Simple way to Call Javascript in Blazor Application

In this blog post, we will discuss how to call JavaScript in Blazor application.

Blazor is a new framework provided by Microsoft to build interactive client-side web applications using C# programming language and Razor syntax on top of the .NET Core framework. The beauty of this framework is that the developer need not know any JavaScript and can leverage the existing .NET, .NET Core frameworks and its associated NuGet packages to power the Blazor application. The developer can build a Blazor application that can run on the server or directly inside the client browsers.

Blazor allows to build the complete client-side application without using JavaScript, but what if you want to use JavaScript into your application or you want to use an already existing functionality that is available as a JavaScript library, well that can be achieved using the JavaScript Interoperability or JSInterop provided by the framework.

With the help of JSInterop, the user can invoke JavaScript functions from .NET methods and .NET methods from JavaScript.

Calling JavaScript in Blazor using IJSRuntime Abstraction

To call the JavaScript method from .NET, the user can use the IJSRuntime abstraction. This abstraction offers the two overloaded InvokeAsync<T> methods. The first method accepts the function name (identifier) and any number of arguments that the function requires as an argument. These JavaScript functions identifiers are relative to the global window scope.

ValueTask<TValue> InvokeAsync<TValue>(string identifier, object[] args);
ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken cancellationToken, object[] args);

The second overloaded method accepts three arguments, the first one being the name of the function identifier, the second one is the CancellationToken (pass the value if you want to cancel the operation in between) and the third is the number of arguments that you want to pass the method as input.

The two important points to remember while using the InvokeAsync<T> method is that the number of arguments being passed to the method as input must be JSON serializable and the second point to remember is that these methods are asynchronous in nature.

A simple call to use the InvokeAsync<T> method would something like the below code.

var result = await JSRuntime.InvokeAsync<string>("function name", input);

Calling JSRuntime from a Component

In order to call a JavaScript function first, we need to add the JavaScript file into the wwwroot folder. (You can add anywhere in the project)

Calling Javascript in Blazor Application
Add JavaScript file in wwwroot folder

Just for reference, a single method is added into the custom.js file that returns the current date and time. The content of the file is as follows:

 function getDateTime() {
    return new Date();

The second step is to add the script tag inside the _Host.cshtml file so that JavaScript is available through the application.

Calling Javascript in Blazor Application _HOST.cshtml
add script in _Host.cshtml

The third step is to inject the JSRuntime dependency on our component.

@inject IJSRuntime JSRuntime

The fourth and final step is to call the JavaScript function. In order to demo that we have created a simple UI having a button that when clicked will call the invokes the getDateTime function and update the UI.

@page "/mycomponent"
@inject IJSRuntime JSRuntime

        <p>Current DateTime:<b> @CurrentDate</b></p>
        <br />
        <input type="button" @onclick="@GetCurrentDateTime" value="Get Current DateTime" />

@code {

    public string CurrentDate { get; set; }

    private async void GetCurrentDateTime()
        CurrentDate = await JSRuntime.InvokeAsync<string>("getDateTime");

The UI of the component is as follows:

Calling JavaScript in Blazor using C# class

The second way to call the JavaScript function is from the C# class, for this we need to inject the IJSRuntime into the class and invoke the method. The sample class to call the above-mentioned functionality is as follows:

using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;

namespace ServerApplication.Data
    public class CurrentDateTime
        IJSRuntime runtime;

        public CurrentDateTime(IJSRuntime runtime)
            this.runtime = runtime;

        public async Task<string> GetDateTime()
            var result = await runtime.InvokeAsync<string>("getDateTime");
            return DateTime.Parse(result).ToString();

This concludes the post about the calling Javascript in Blazor Application and I hope you found this post helpful. Thanks for visiting, Cheers!!!

[Further Readings: Creational Design Patterns |  Builder Design Pattern in C# |  Prototype Design Pattern in C# |  Top 5 Blazor Component Libraries |  Abstract Factory Design Pattern in C# |  Factory Method Pattern in C# |  Singleton Design Pattern in C# |  Introduction to Design Patterns |  Microsoft C# Version History |  Microsoft .NET Core Versions History |  Microsoft .NET Framework Version History |  Introduction to WPF in .NET Core |  Useful Visual Studio 2019 extensions for database projects |  Machine Learning Model Generation |  Important Global Visual Studio 2019 Shortcuts   ]  

4 1 vote
Article Rating
Notify of
1 Comment
newest most voted
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x