How to use JavaScript in Blazor

Some things are simply not possible to do in Blazor without JavaScript. If you need to access things like local storage or make some kinds of interactivity possible we will need to make JS calls. So how do we call JS from C#?

To make this happen we will use a feature that is baked into Blazor that requires no configuration or setup: IJSRuntime. Let's start with a new Blazor project and go to the Index page. There at the top of the file, we need to inject our IJSRuntime:

@inject IJSRuntime jsRuntime

And as simple as that, we can make JS calls! Let's try it out by using a native JS function to write to the console. Add a button with an onclick handler like this:

<button @onclick="Click">
    Click me!
</button>

@code {
    private async Task Click()
    {
        await jsRuntime.InvokeVoidAsync("console.log", "Hello, World!");
    }
}

When you click the button you'll see Hello, World! in the console in your browser. This also works for objects and other primitive types:

private async Task Click()
{
    user = new User { Name = "Manny", Id = 7 };
    await jsRuntime.InvokeVoidAsync("console.log", user);
    await jsRuntime.InvokeVoidAsync("console.log", "Hello, World!");
    await jsRuntime.InvokeVoidAsync("console.log", 42);
    await jsRuntime.InvokeVoidAsync("console.log", true);
}

That's all great, but what if you want to call some of your own JS that lives in its own file? I'm glad you asked! First, we need to make sure the JS file is loaded into the page by adding it to index.html. Let's say you have a file app.js in wwwroot/js/. Add it to index.html like this:

// app.js
function doSomething(param) {
    console.log("my param is " + param);
}
<body>
    ...
    <script src="_framework/blazor.webassembly.js"></script>
    <script src="js/app.js"></script>
</body>

Then just call the function the same way you did before

await jsRuntime.InvokeVoidAsync("doSomething", "awesome");

That's it! You're now calling your code and making things happen. Now, what if we want to get a return value from our JS function? InvokeVoidAsync is specific for functions that return void (as the name implies). There is another method that handles a return type: InvokeAsync<>. Let's add a function to our app.js

function getMeaningOfLife() {
    return 42;
}

Then call the function in our Click handler

private async Task Click()
{
    Number = await jsRuntime.InvokeAsync<int>("getMeaningOfLife");
}

This works for other primitive types and objects as long as you can deserialize them.

function getUser() {
    return { name: "Manny", id: 7 };
}
public class User
{
    public string Name { get; set; }
    public int Id { get; set; }
}
...
private async Task Click()
{
    var user = await jsRuntime.InvokeAsync<User>("getUser");
}

I hope you found this helpful, let me know if it did. Happy coding!

Did you find this article valuable?

Support Ryan Phillips by becoming a sponsor. Any amount is appreciated!