JavaScript Interop
By Syncfusion®, Inc. · Last updated
JavaScript interop in Blazor: when to use it, adding JavaScript files, IJSRuntime with InvokeAsync and InvokeVoidAsync, arguments and return values, sync calls, modules, interop timing, [JSInvokable] and DotNetObjectReference, JSException and disposing references.
What you will learn
- Add JavaScript files and call them with IJSRuntime
- Pass values to JavaScript and read the results
- Load JavaScript modules and call JavaScript at the right time
- Call C# from JavaScript, handle errors and dispose references
JavaScript Interop Overview
- JavaScript is the language every browser runs. Most websites use it for things like copying text or saving data in the browser.
- Interop (short for interoperability) means two languages working together.
- JavaScript interop (JS interop) lets your C# code call JavaScript functions, and lets JavaScript call your C# methods.
- Blazor does most work in C#. JS interop is the door to browser features that only JavaScript can reach.
Real-World Example:
- Ravi wants a Copy coupon button that puts "TEA10" on the customer's clipboard.
- He also wants the shop to remember the customer's name in the browser.
- Both are browser features. His C# calls a small JavaScript function for each one.
Animation: two islands, C# with Blazor on the left and JavaScript with the browser on the right, joined by a bridge called JS interop. A dot crosses from C# to JavaScript carrying greet("Asha"), then a dot comes back carrying "Hello, Asha".
C# (Blazor) your components
JavaScript clipboard, storage...
JS interop bridge greet("Asha") → ← "Hello, Asha"
JS interop is a bridge: C# calls JavaScript, and the answer comes back.
When to Use JS Interop
- Use it for browser features that Blazor does not have, like the clipboard,
localStorageor the page's scroll position. - Use it to reuse a JavaScript library, like a chart or a map.
- Do not use it for things Blazor already does: showing and hiding, clicks,
@bindand changing text. Plain C# is simpler there.
| Task | JS interop? |
|---|---|
| Copy text to the clipboard | Yes |
Save a value in localStorage | Yes |
| Draw a chart with a JS library | Yes |
| Show a message when a button is clicked | No, use @onclick |
| Hide a panel | No, use @if |
Blazor owns the HTML it renders. Do not let JavaScript change those elements, or Blazor and JavaScript will fight over them.
Adding JavaScript Files
- JavaScript files go in the
wwwrootfolder, for examplewwwroot/js/tea.js. Files inwwwrootare sent to the browser as they are. - Load the file in
Components/App.razor, after Blazor's own script, with a<script>tag. - Put your functions on one object, like
window.teaShop. Then C# can call them by name, liketeaShop.greet.
A component can also have its own JavaScript file next to it, like Order.razor.js. It is loaded as a module. You learn modules below.
Calling JavaScript from C#
IJSRuntime
IJSRuntimeis Blazor's service for calling JavaScript. A service is a ready-made helper that Blazor gives you.- Get it with
@inject IJSRuntime JSat the top of the component. - Then call a function by its name:
JS.InvokeAsync<string>("teaShop.greet", "Asha").
In the below example, tea.js defines teaShop.greet. The button in Home.razor calls it and shows the answer.
Async Calls (InvokeAsync, InvokeVoidAsync)
- Async means "do not wait and freeze the page". The call finishes later, and
awaitwaits for it without blocking. InvokeAsync<T>calls a function and gets a value back of typeT.InvokeVoidAsynccalls a function that returns nothing, like "save this".
In the below example, Save uses InvokeVoidAsync to store the name in localStorage. Load uses InvokeAsync<string> to read it back.
Passing Arguments and Return Values
- You can pass numbers, strings, lists and objects. Blazor turns them into JSON: a text format that both C# and JavaScript understand.
- A returned JavaScript object becomes a C# object when the property names match (upper or lower case does not matter).
In the below example, C# passes cups and price to teaShop.bill. JavaScript returns an object with total and message, and C# reads it as a Bill record.
Sync Calls (IJSInProcessRuntime)
- Sync means the call finishes right away, with no
await. - In Interactive WebAssembly, C# and JavaScript run in the same browser, so a sync call is possible.
- Cast
JStoIJSInProcessRuntimeand useInvoke<T>. It does not work in Interactive Server, where JavaScript is far away in the browser.
In the below example, Invoke<int> gets the window width at once, with no await.
JavaScript Modules (IJSObjectReference)
- A module is a JavaScript file that exports its functions with
export. Nothing is added towindow, so names do not clash. - C# loads a module with
JS.InvokeAsync<IJSObjectReference>("import", "./js/discount.js"). IJSObjectReferenceis a reference: a handle that points to the loaded module. Call its functions through it.- No
<script>tag is needed inApp.razorfor a module.
In the below example, Home.razor imports discount.js once, in OnAfterRenderAsync, and calls its discount function.
Interop Timing (OnAfterRenderAsync)
- During prerendering (see Server Rendering), there is no browser yet, so JavaScript cannot run.
- Also, an element exists in the browser only after the component renders.
- So call JavaScript in
OnAfterRenderAsync, usually only whenfirstRenderistrue. Not inOnInitialized. @refstores an element in a C# field of typeElementReference, so you can pass it to JavaScript.
Animation along a timeline: OnInitialized, then Render, then OnAfterRenderAsync. A red cross on OnInitialized says too early: no element yet. A green tick on OnAfterRenderAsync says the element exists: call JavaScript here.
OnInitialized
Render
OnAfterRenderAsync
✗ too early: no element ✓ call JavaScript here
Call JavaScript after the render, when the elements exist in the browser.
In the below example, @ref stores the name box in nameBox. In OnAfterRenderAsync, teaShop.focus puts the cursor in it.
- For focus only, Blazor also has a shortcut with no JavaScript:
await nameBox.FocusAsync();.
Calling C# from JavaScript
- Sometimes JavaScript must tell C# something, for example when a JavaScript timer or library finishes.
- Mark the C# method with
[JSInvokable], so JavaScript is allowed to call it.
Static Methods ([JSInvokable])
- A static method belongs to the class, not to one component. It cannot change the fields of a component on the page.
- JavaScript calls it with
DotNet.invokeMethodAsync("AssemblyName", "MethodName"). - The assembly name is your project's name, like
"TeaShop". In the code box it changes on every Run, so C# passes it to JavaScript.
In the below example, JavaScript asks the static C# method GetSpecial for today's special.
Instance Methods (DotNetObjectReference)
- An instance method belongs to one component on the page, so it can change its fields.
DotNetObjectReference.Create(this)makes a reference to the component. Pass it to JavaScript.- JavaScript calls
reference.invokeMethodAsync("MethodName"). In C#, the method has[JSInvokable]and callsStateHasChanged()to update the page.
In the below example, JavaScript starts a 2-second tea timer. When it ends, it calls TeaReady on this component.
Animation: C# passes a reference card labelled Home component to JavaScript. Two seconds later, JavaScript uses the card to call TeaReady back on the same component, which shows Your tea is ready.
Home component Brewing... Your tea is ready!
JavaScript setTimeout(2000) reference → ← TeaReady()
JavaScript keeps the reference and uses it to call the same component back.
Practical Uses
Common jobs for JS interop in a Blazor app:
- Clipboard: copy a coupon code with
navigator.clipboard.writeText. - Browser storage: remember values with
localStorage. - Scrolling: jump to the top of a long page with
window.scrollTo. - Libraries: draw charts or maps with a JavaScript library.
In the below example, Copy coupon puts "TEA10" on your clipboard. Paste it anywhere to check.
Interop Errors (JSException)
- If the JavaScript function does not exist, or it throws an error, C# gets a
JSException. - An exception is how C# reports an error. Without handling it, the component breaks.
- Catch it with
tryandcatch (JSException ex), and show a friendly message.
In the below example, teaShop.print does not exist. The catch block shows a friendly message instead of breaking the page.
In Interactive Server, a call can also fail with JSDisconnectedException when the user has closed the tab. You can safely ignore it in Dispose.
Disposing JS References
- Disposing means releasing something you no longer need, so it does not keep using memory.
- An
IJSObjectReference(a module) keeps JavaScript memory. Callawait module.DisposeAsync(). - A
DotNetObjectReferencekeeps your component alive for JavaScript. Callself.Dispose(). - Do both when the component is removed: use
@implements IAsyncDisposableorIDisposable, as you learned in Component Lifecycle.
- The module and instance examples above already dispose their references this way.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Calling JavaScript in OnInitialized | The browser is ready at once | Call it in OnAfterRenderAsync with firstRender | An error during prerendering |
| Changing Blazor's elements with JavaScript | Both can edit the same HTML | Let Blazor own its HTML. Use JS only for browser features | The page shows wrong or broken content |
InvokeAsync without a type for a function that returns nothing | Every call needs a return type | Use InvokeVoidAsync | A build error or a wrong value |
Using IJSInProcessRuntime in Interactive Server | Sync calls work everywhere | Use it only in WebAssembly | An error: the cast fails |
A C# method called from JS without [JSInvokable] | Any public method can be called | Add [JSInvokable] | JavaScript gets an error |
Never disposing a DotNetObjectReference | Blazor cleans it up | Dispose it in Dispose | The component stays in memory |
Check Yourself
Exercises
What to Remember
- JS interop lets C# call JavaScript and JavaScript call C#. Use it only for browser features and JS libraries.
- Put JavaScript in
wwwroot/jsand load it inApp.razorafterblazor.web.js. Modules need no script tag. @inject IJSRuntime JS, thenInvokeAsync<T>for a value orInvokeVoidAsyncfor no value. Arguments and results travel as JSON.IJSInProcessRuntime.Invoke<T>is a sync call, for WebAssembly only.- Load a module with
InvokeAsync<IJSObjectReference>("import", path). - Call JavaScript in
OnAfterRenderAsyncwhenfirstRenderis true. - JavaScript calls C# with
[JSInvokable]: static withDotNet.invokeMethodAsync, instance withDotNetObjectReference. - Catch
JSException. Dispose module and object references when the component is removed.
Next: Dependency Injection