use-js-interop
What it does
This skill guides calling JavaScript from Blazor components and calling .NET code from JavaScript. It is for .NET developers who need a browser feature, such as a chart library or canvas, inside a Blazor page.
When to use it
- βWhen a Blazor component needs a JavaScript library such as a chart or map.
- βWhen JavaScript needs to call back into a Blazor component.
- βWhen JavaScript references cause errors or leaks after a component is removed.
Skill link
https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.mdCopy it and paste it into your AI (Claude, ChatGPT or Cursor), asking it to follow the instructions.
How to use
The easiest way: copy the message and paste it into your AI. It reads the skill and follows the instructions.
Ready-to-paste message
For Claude Code, Codex or Cursor: run it in your project folder and the skill gets installed.
Download the SKILL.md and drop it into your agentβs skills folder.
Example of what to ask your AI
βAdd a canvas chart to my Blazor page using a small JavaScript module that the component can call.β
5 new skills a week. 1 minute to read.
How it works
The agent places a JavaScript module next to the component, calls it only after the page has rendered, and cleans up the references when the component is removed.
Technical content (original SKILL.md)
Original text by the author, straight from GitHub.
JS Interop in Blazor
1. Collocated JS Modules
Always use collocated .razor.js files with export β never global window.* functions or <script> tags.
// ChartPanel.razor.js β placed next to ChartPanel.razor
export function initialize(canvas, dotNetRef) { /* ... */ }
export function updateData(points) { /* ... */ }
export function dispose() { /* ... */ }
Import paths: same project = "./Components/ChartPanel.razor.js", RCL = "./_content/{AssemblyName}/...".
2. Lifecycle Timing
All JS interop must happen in OnAfterRenderAsync or event handlers β never in OnInitialized, OnParametersSet, or constructors. JS is not available during server prerendering.
Use a typed interop wrapper (see Section 4) β never call InvokeAsync/InvokeVoidAsync with raw string literals:
private ChartInterop? _chart;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
_chart = new ChartInterop(JS);
await _chart.InitializeAsync(_canvasRef);
}
}
Parameter changes: set a flag in OnParametersSet, apply in OnAfterRenderAsync:
private bool _dataChanged;
protected override void OnParametersSet() => _dataChanged = true;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender) { /* init */ }
else if (_dataChanged && _chart is not null)
{
_dataChanged = false;
await _chart.UpdateDataAsync(DataPoints);
}
}
3. Batch Related Operations
Each JS interop call crosses the .NET-to-JS boundary (and in Blazor Server, the SignalR circuit). Batching applies in both directions β .NETβJS and JSβ.NET.
.NET β JS: merge consecutive calls
If the C# side makes two or more JS calls in a row, combine them into one JS function:
// β Two round-trips β theme and locale are always applied together
await _module.InvokeVoidAsync("applyTheme", theme);
await _module.InvokeVoidAsync("applyLocale", locale);
// β Result of one call feeds into another β both can stay in JS
var token = await _module.InvokeAsync<string>("createAccessToken");
await _module.InvokeVoidAsync("storeToken", token);
// β
One call applies both β no data dependency, no reason for two trips
export function applyPreferences(theme, locale) {
document.documentElement.dataset.theme = theme;
document.documentElement.lang = locale;
}
// β
Chain stays in JS β the token never needs to cross the boundary
export function createAndStoreToken() {
const token = crypto.randomUUID();
sessionStorage.setItem('access-token', token);
return token;
}
JS β .NET: batch callbacks
When JS needs to send multiple pieces of data back to .NET, send them in a single invokeMethodAsync call rather than making separate callbacks:
// β Two .NET round-trips from JS
await dotNetRef.invokeMethodAsync(ON_VOLUME_CHANGED, volume);
await dotNetRef.invokeMethodAsync(ON_PLAYBACK_CHANGED, isPlaying);
// β
One callback with all data
await dotNetRef.invokeMethodAsync(ON_PLAYER_STATE_CHANGED, { volume, isPlaying });
Rule: if two interop calls always happen together from either side, merge them into one function.
4. Typed Interop Wrapper
Encapsulate interop for a feature in a plain class that owns the module lifecycle:
public sealed class ChartInterop : IAsyncDisposable
{
internal const string ModulePath = "./Components/ChartPanel.razor.js";
internal const string InitMethod = "initialize";
internal const string UpdateMethod = "updateData";
internal const string DisposeMethod = "dispose";
private readonly IJSRuntime _js;
private IJSObjectReference? _module;
public ChartInterop(IJSRuntime js) => _js = js;
private async ValueTask<IJSObjectReference> GetModuleAsync()
=> _module ??= await _js.InvokeAsync<IJSObjectReference>("import", ModulePath);
public async ValueTask InitializeAsync(ElementReference canvas)
{
var module = await GetModuleAsync();
await module.InvokeVoidAsync(InitMethod, canvas);
}
public async ValueTask UpdateDataAsync(IReadOnlyList<DataPoint> points)
{
var module = await GetModuleAsync();
await module.InvokeVoidAsync(UpdateMethod, points);
}
public async ValueTask DisposeAsync()
{
try
{
if (_module is not null)
{
await _module.InvokeVoidAsync(DisposeMe
FAQ
Can JavaScript run during server prerendering?
No. The skill keeps JavaScript calls after rendering, because JavaScript is not available during prerendering.
Does it use global scripts?
No. It uses collocated modules with exported functions instead of global script tags.
What about cleanup?
It covers disposing of JavaScript references when components are removed.
Details
Original description by the author
Add, review, or fix JavaScript interop in Blazor components. USE FOR: calling JavaScript from Blazor, calling .NET from JavaScript, collocated .razor.js modules, IJSRuntime, IJSObjectReference lifecycle, DotNetObjectReference, ElementReference, timing rules for when JS is available, IAsyncDisposable disposal of JS references, server-side JS interop safety. DO NOT USE FOR: general Blazor component authoring without JS interop needs (use author-component), forms (use collect-user-input).
repo: dotnet/skills
Popularity
- GitHub stars
- 5.8k
- Ranking position
- #14570
- License
- MIT
- Updated
- 11/2/2026
Comments
- β¦
More skills from this repository
create-custom-agent
5.8kHelps your agent create VS Code custom agent files with their own tools, instructions and handoffs to other agents.
create-skill
5.8kHelps your agent create a new agent skill with a valid name, a clear trigger description and a SKILL.md file that follows the standard.
csharp-scripts
5.8kHelps your agent run a small C# program as a single file with the .NET command line tool, without creating a full project.
dotnet-pinvoke
5.8kHelps your agent call native C or C++ libraries from .NET correctly, covering signatures, string handling, memory and safe handles.
Similar skills
angular-developer
280kHelps your agent create Angular code and give project structure advice. Useful for starting new projects, creating code parts, or improving performance and accessibility.
frontend-a11y
280kHelps your agent make web interfaces accessible to everyone. It ensures websites and apps work well with screen readers and keyboard navigation.
frontend-patterns
280kHas your agent apply modern patterns in frontend development. It optimizes performance, manages state, and follows best practices in React and Next.js.