Live Chat Icon For mobile
Live Chat Icon

How do you call a JavaScript function from .NET using JavaScript Interop?

Platform: Blazor| Category: JavaScript Interop

In Blazor, IJSRuntime interface is used to invoke a JavaScript function from .NET.

Using the InvokeAsync<T> method of IJSRuntime abstraction, we can call the JavaScript function. This method takes the function name and function parameters as the argument.

Task<T> InvokeAsync<T>(string identifier, params object[] args);

The JavaScript function should always be written in the index.html file. Open the wwwroot/index.html file and put in the following code.

<html>
<head></head>
<body>
    <app>Loading...</app>

    <script src="_framework/blazor.webassembly.js"></script>
    <script>
        function JSMethod() {
            document.getElementById('demop').innerText = "Javascript Method Invoked";
        }
</body>
</html>

Open JSInterop.cshtmland put in the following code.

@page "/jsinterop"
@inject IJSRuntime JsRuntime;

<h1>JavaScript Interop</h1>

<hr />

<button class="btn btn-primary" @onclick="@CallJSMethod">Call JS Method</button>

<br />
<div id="demop"></div>

@code {
    Protected async void CallJSMethod()
    {
        await JSRuntime.InvokeAsync<string>("JSMethod");
    }
}

The method CallJSMethod will call JS function JSMethod by using the JSRuntime.InvokeAsync method.

Important notes

  • Do not write your JS code in the .cshtml file. This is not allowed in Blazor and the compiler will throw an error. Always put your JS code in the wwwroot/index.html file.
  • Always add your custom <script> tag after “<script src=”_framework/blazor.webassembly.js”> </script>” in the <body> section of the index.html file. This is to ensure that your custom script will execute after loading the “blazor.webassembly.js” script.

Reference link

https://www.freecodecamp.org/news/how-to-implement-javascript-interop-in-blazor-9f91d263ec51/

Share with

Share on twitter
Share on facebook
Share on linkedin

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.