Posts How to invoke Javascript function from within C# in Blazor
Post
Cancel

How to invoke Javascript function from within C# in Blazor

Previously, I wrote about having developed and deployed a web app to generate GUID using Blazor and deployed using Azure Static Web App.

I came across this challenge of wanting to invoke a Javascript function in the web app. Well, this is how you do it.

First of all, I was using Blazor WebAssembly App, and in my scenario using javascript instead of C# seemed the right and easy way to go for it.

This is how your razor file would look like.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@page "/"
@inject IJSRuntime jsRuntime

<div class="copy-div">
    <i class="fa fa-copy copy-button" @onclick="()=>CopyItem("item")"></i>
    <img class="arrow" src="./img/blue.png" />
</div>

</div>

@code {
    private void CopyItem(string item)
    {
        jsRuntime.InvokeAsync<String>("copyItem", item);
    }
}

Now, create the file Something.js (or, in this example CopyItem.js) in the wwwroot folder (in this example, it is wwwroot\js). Write the javascript function to this file.

1
2
3
4
function copyItem(item) {
    console.log(item);
    navigator.clipboard.writeText(item);
}

Don’t forget to add the script reference to index.html file.

1
<script src="./js/Something.js"></script>

This should do the trick.

You can checkout a complete solution implementation here.

This post is licensed under CC BY 4.0 by the author.