Tutorials Blazor Architecture & Enterprise Patterns

JS Interop: Calling JavaScript from C# and vice versa

On this page

Crossing the Bridge

Even though Blazor lets you avoid Javascript, there are times you **must** use it—for charts, maps, or legacy libraries. This is JS Interop.

1. IJSRuntime (C# to JS)

Inject IJSRuntime into your component. You can then call any global Javascript function using InvokeVoidAsync or InvokeAsync<T>. await JS.InvokeVoidAsync("alert", "Hello from C#!");. Always use the Async versions to avoid blocking the SignalR thread.

2. [JSInvokable] (JS to C#)

You can also call C# from Javascript. Mark a public method as [JSInvokable]. You then pass a DotNetObjectReference to Javascript, allowing it to call back into your specific component instance. This is vital for wrapping complex JS libraries that have their own event systems (like Google Maps).

3. Architect Insight

Q: "How do I prevent JS Interop memory leaks?"

Architect Answer: "Always dispose of your DotNetObjectReference objects. If you pass a reference to JS and don't clean it up when the component is destroyed, the GC can never reclaim that component's memory. Use IDisposable and tell Javascript to drop the reference in the Dispose method."

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

Blazor Architecture & Enterprise Patterns
Course syllabus
1. Blazor Foundations
2. Component Architecture
3. Data & State Management
4. SignalR & Interactivity
5. Security & Data Protection
6. Advanced Performance
7. Testing & CI/CD
8. The Blazor Architect's Case Study
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details