Skip to content
Skillpedia
Websites & UI (frontend)5.8k Β· #14570

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.md

Copy 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

Use this skill to help me: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
Want your AI to find skills like this on its own?Install the free Skillpedia MCP: one line, and it searches 15,000+ skills before each task.Install in 1 minute β†’

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

Is this skill useful?

0

Sign in to vote.

Comments

  • …

More skills from this repository

Similar skills