Introduction
In this article, we will be learning how to invoke JavaScript functions in a Blazor application. Sometimes, we want to use JavaScript functions from our Blazor application. To be able to do this, Blazor offers a service called JS runtime service. For example, using the application that we have been building we might want to delete a book. The delete function is already there but we would want the application to bring up a notification or dialog box that would say “Would you want to delete the book”. This notification or a dialog box would have a button to confirm and to cancel the delete request. If the user clicks the button to confirm, the application will then delete the book, but if they click cancel, the application would then cancel the deletion of the book title. This is mainly done to avoid errors when the user is using the application. We can do this by using the confirm function in JavaScript. The following steps are required in order to do this:
Step 1
Go to Visual Studio.
Step 2
Go to the Booklist component.
Step 3
We have to inject the IJSRuntime service by putting the following code in figure 1 below.
Step 4
Go to the delete method in the component.
Step 5
Change it from void to async task.
Step 6
Inside the delete method, declare a variable of type var and call it confirmed as illustrated in figure 2 below.
Step 7
We are going await and the js.invokeasync of type book as illustrated in figure 2 below.
Step 8
And then we pass the name of the JavaScript function that we would like to use in this case which is the confirm function and the argument that we would like to use for example “Are you sure you want to delete book” as illustrated on figure 2 below.
Step 9
Put an if statement which would delete the book only if the variable confirmed is true, as illustrated in figure 2 below:
- private async Task DeleteBook(Books books) {
- var confirmed = await js.InvokeAsync < bool > ("confirm", $ "Are you sure you want to delete {books.Tittle } ?");
- if (confirmed) {
- book.Remove(books);
- }
- }

Join the conversation! Your thoughts help the community grow.