Official agent skill

Use JS Interop

by dotnet in dotnet/skills

Add, review, or fix JavaScript interop in Blazor components.

OfficialMITAuto-check passedBackend & APIs

Install Use JS Interop

skills CLI
$ npx skills add dotnet/skills --skill use-js-interop -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install dotnet/skills use-js-interop --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/dotnet/skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/plugins/dotnet-blazor/skills/use-js-interop .claude/skills/use-js-interop && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
use-js-interop
GitHub stars
5.6k
Used in
1 other repo
Token cost
~2.7k tokens
SKILL.md length
622 words
Files
1
Skills in repo
91
Repo updated
First seen
Licence
MIT

At a glance

Add, review, or fix JavaScript interop in Blazor components.

  • Works in 7 steps: Collocated JS Modules → Lifecycle Timing → Batch Related Operations → …
  • : calling JavaScript from Blazor
  • SKILL.md covers 1. Collocated JS Modules, 2. Lifecycle Timing, 3. Batch Related Operations and 4. Typed Interop Wrapper, plus 5 more sections
  • Instructions only: no scripts, shell commands, URLs or credentials in SKILL.md

What it does

Use JS Interop is an agent skill from dotnet/skills, published by the product's own GitHub organization. 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).

Its SKILL.md is about 2.7k tokens, which your agent loads only when the skill is triggered. It is a single SKILL.md file with no bundled scripts.

It sits in Backend & APIs, covering Backend development. It works with Blazor, .NET, JavaScript and C#. The repository describes itself as: Repository for skills to assist AI coding agents with .NET and C. The licence is MIT.

When your agent uses it

  • : calling JavaScript from Blazor
  • Calling .NET from JavaScript
  • Collocated .razor.js modules
  • IJSObjectReference lifecycle

Example prompts

  • “/use-js-interop”

Workflow steps

7 steps, taken from the step headings in SKILL.md.

  1. Collocated JS Modules
  2. Lifecycle Timing
  3. Batch Related Operations
  4. Typed Interop Wrapper
  5. DotNetObjectReference for JS-to-.NET Callbacks
  6. Disposal and Server Safety
  7. ElementReference

What it can do on your machine

Read from SKILL.md and the folder at commit 8d670fa. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are csharp, javascript and razor).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Use JS Interop loads about 2.7k tokens when it runs. Until then it costs about 126 tokens; SKILL.md has 622 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~126
When it runs · the whole SKILL.md, loaded when a task matches
~2.7k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from dotnet/skills at commit 8d670fa, republished under its MIT licence (© dotnet). 622 words, ~2,731 tokens.

Download SKILL.mdSave it as .claude/skills/use-js-interop/SKILL.md (or your agent's skills folder).
name
use-js-interop
description
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).
license
MIT

JS Interop in Blazor

1. Collocated JS Modules

Always use collocated .razor.js files with export — never global window.* functions or <script> tags.

javascript
// 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:

csharp
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:

csharp
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);
    }
}

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:

csharp
// ❌ 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);
javascript
// ✅ 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:

javascript
// ❌ 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:

csharp
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(DisposeMethod);
                await _module.DisposeAsync();
            }
        }
        catch (JSDisconnectedException) { }
    }
}

The component creates and uses the wrapper with no magic strings:

razor
@inject IJSRuntime JS
@implements IAsyncDisposable

<canvas @ref="_canvasRef" width="600" height="400"></canvas>

@code {
    private ElementReference _canvasRef;
    private ChartInterop? _chart;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            _chart = new ChartInterop(JS);
            await _chart.InitializeAsync(_canvasRef);
        }
    }

    async ValueTask IAsyncDisposable.DisposeAsync()
    {
        if (_chart is not null)
            await _chart.DisposeAsync();
    }
}

Prefer a concrete class over interface + implementation for interop wrappers. For unit testing, substitute IJSRuntime directly (it is already an interface).

5. DotNetObjectReference for JS-to-.NET Callbacks

csharp
_dotNetRef = DotNetObjectReference.Create(this);
await _module.InvokeVoidAsync("initialize", _dotNetRef);

On the JS side, wrap the dotNetRef in a class. Use async/await with try/catch (not .catch()) to guard against circuit loss. Define .NET method name constants at the top:

javascript
const ON_CLIPBOARD_CHANGED = 'OnClipboardChanged';

class ClipboardMonitor {
    #dotNetRef;
    #abortController;

    constructor(dotNetRef) {
        this.#dotNetRef = dotNetRef;
        this.#abortController = new AbortController();
    }

    start() {
        document.addEventListener('copy', async () => {
            try {
                const text = await navigator.clipboard.readText();
                await this.#dotNetRef.invokeMethodAsync(ON_CLIPBOARD_CHANGED, text);
            } catch { /* circuit disconnected or clipboard denied */ }
        }, { signal: this.#abortController.signal });
    }

    dispose() {
        this.#abortController.abort();
    }
}

let monitor;
export function initialize(dotNetRef) {
    monitor = new ClipboardMonitor(dotNetRef);
    monitor.start();
}

export function dispose() {
    monitor?.dispose();
}

Rules:

  • [JSInvokable] methods must be public — private/internal silently fails at runtime
  • Wrap StateHasChanged in InvokeAsync inside [JSInvokable] callbacks:
    csharp
    [JSInvokable]
    public async Task OnClipboardChanged(string text)
    {
        await InvokeAsync(() => { _lastClipboard = text; StateHasChanged(); });
    }
  • Always try/catch around invokeMethodAsync in JS — circuit loss throws
  • Use const for .NET method name strings in JS — prevents typo bugs that silently fail
  • Dispose DotNetObjectReference in DisposeAsync

6. Disposal and Server Safety

Always implement IAsyncDisposable. Call JS cleanup first, then dispose references. Catch JSDisconnectedException for Blazor Server circuit loss:

csharp
public async ValueTask DisposeAsync()
{
    try
    {
        if (_module is not null)
        {
            await _module.InvokeVoidAsync("dispose");
            await _module.DisposeAsync();
        }
    }
    catch (JSDisconnectedException) { }

    _dotNetRef?.Dispose();
}

Never use sync IDisposable for JS interop cleanup — InvokeVoidAsync returns ValueTask and must be awaited.

7. ElementReference

Pass DOM elements via @ref, not string IDs:

razor
<canvas @ref="_canvasRef" width="600" height="400"></canvas>
csharp
await _chart.InitializeAsync(_canvasRef);
Show full SKILL.md (270 more words)Show less

Checklist

  • JS is in collocated .razor.js with export — no window.* globals
  • All interop in OnAfterRenderAsync or event handlers — never during prerender
  • IAsyncDisposable catches JSDisconnectedException
  • DotNetObjectReference disposed in DisposeAsync; JS side has try/catch around invokeMethodAsync
  • [JSInvokable] methods are public and use await InvokeAsync(StateHasChanged)
  • InvokeVoidAsync used when no return value is needed
  • ElementReference instead of string IDs
  • Related operations batched into single interop calls (both .NET→JS and JS→.NET)

Common Mistakes Checklist

MistakeFix
Using JS for something achievable with CSSUse CSS custom properties, data- attributes, pseudo-classes
Many fine-grained interop callsBatch into coarse functions — both .NET→JS and JS→.NET
Component imports JS module directlyEncapsulate in a strongly typed interop class
Magic strings for method names / module pathsDefine internal const fields in the interop class
Interface + implementation for interop wrapperUse a plain class; mock IJSRuntime for tests instead
JS calls in OnInitializedAsyncMove to OnAfterRenderAsync(firstRender)
InvokeAsync<object> for void callsUse InvokeVoidAsync
IDisposable with fire-and-forget JSUse IAsyncDisposable with await
Global window.* JS functionsUse collocated .razor.js with export
String element IDs passed to JSUse ElementReference with @ref
[JSInvokable] on private methodMust be public — silently fails otherwise
DotNetObjectReference not disposedDispose in DisposeAsync — causes memory leak
StateHasChanged() without InvokeAsyncWrap in await InvokeAsync(() => { StateHasChanged(); })
JS invokeMethodAsync without error handlingWrap in try/catch — circuit loss throws
Bare dotNetRef in JS event handlersWrap in a class with #dotNetRef private field
Magic strings in JS invokeMethodAsync callsUse const at module top — typos silently fail at runtime
JS calls in OnParametersSetAsyncTrack changes, apply in OnAfterRenderAsync with guard
No null check before calling moduleCheck module is not null before use

© dotnet, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

Just SKILL.md in plugins/dotnet-blazor/skills/use-js-interop of dotnet/skills.

Open the folder on GitHubat commit 8d670fa

Used in 1 other repository

We found 2 copies of this SKILL.md (exact, near-identical or edited) in other folders, from 1 other GitHub owner. This page covers the copy in dotnet/skills, which our catalogue first saw on October 7, 2026.

Compare with similar skills

Use JS Interop next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Use JS Interop compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Use JS Interop this skilldotnet/skills5.6k1 repos~2.7kAutomated safety check: PassMIT
C# and .NET DeveloperJeffallan/claude-skills12k—~1.3kAutomated safety check: PassMIT
Blazormanagedcode/dotnet-skills486—~2.1kAutomated safety check: PassMIT
Dotnet Backend Patternswshobson/agents40k7 repos~6.6kAutomated safety check: PassMIT
Using Dotnetnovotnyllc/dotnet-artisan233—~2.3kAutomated safety check: WarnMIT
.NET Core ExpertJeffallan/claude-skills12k—~1.3kAutomated safety check: PassMIT

Similar skills

  • C# and .NET Developer

    Jeffallan/claude-skills

    Guides C# work on .NET 8+: ASP.NET Core APIs, Entity Framework Core data access, Blazor apps and CQRS with MediatR, following a five-step build workflow.

    12k GitHub stars~1.3k tokensUpdated 4 days ago
    Backend & APIsAuto-check passed
  • Blazor

    managedcode/dotnet-skills

    Build and review Blazor applications across server, WebAssembly, web app, and hybrid scenarios with correct component design, state flow, rendering, and hosting choices.

    486 GitHub stars~2.1k tokensUpdated today
    Agent WorkflowsAuto-check passed
  • Master C/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications.

    40k GitHub starsUsed in 7 repos~6.6k tokens
    Backend & APIsAuto-check passed
  • Using Dotnet

    novotnyllc/dotnet-artisan

    Detects .NET intent for any C, ASP.NET Core, EF Core, Blazor, MAUI, Uno Platform, WPF, WinUI, SignalR, gRPC, xUnit, NuGet, or MSBuild request from prompt keywords and repository signals (.sln…

    233 GitHub stars~2.3k tokensUpdated 1 mo ago
    Backend & APIsAuto-check: warnings
  • .NET Core Expert

    Jeffallan/claude-skills

    Guides building .NET 8 services with minimal APIs, clean architecture, Entity Framework Core, MediatR CQRS and JWT authentication, with build and test checks.

    12k GitHub stars~1.3k tokensUpdated 4 days ago
    Backend & APIsAuto-check passed
  • Blazor Authentication

    Nethereum/Nethereum

    Implement Sign-In with Ethereum (SIWE / EIP-4361) authentication in Blazor with JWT tokens, session management, and AuthorizeView (.NET/C).

    2.3k GitHub stars~1.8k tokensUpdated 2 days ago
    Backend & APIsAuto-check passed

More from dotnet/skills

All 91 skills in this repo
  • Official

    Resolves .NET runtime frames in Apple .ips crash logs to function names, source files and line numbers using dSYM symbols, atos and the Microsoft symbol server.

    5.6k GitHub starsUsed in 1 repo~2.4k tokens
    Auto-check passed
  • Official

    Resolves native crash frames from .NET Android tombstones to function names, source files and line numbers using BuildIds, Microsoft's symbol server and llvm-symbolizer.

    5.6k GitHub starsUsed in 1 repo~2.1k tokens
    Auto-check passed
  • Official

    Scans C# and .NET code for about 50 performance anti-patterns and reports prioritized findings with concrete fixes, at a scan depth you choose.

    5.6k GitHub starsUsed in 3 repos~3.1k tokens
    Auto-check passed
  • Official

    Statically pairs source files with test files to list code that no test references, using Roslyn for C# or tree-sitter for many languages, with no build.

    5.6k GitHub starsUsed in 1 repo~3.3k tokens
    Auto-check passed
  • Microbenchmarking

    dotnet/skills

    Official

    Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks.

    5.6k GitHub starsUsed in 3 repos~3.3k tokens
    Auto-check passed
  • Official

    Makes .NET projects compatible with Native AOT and trimming by resolving IL trim and AOT analyzer warnings through annotations rather than suppressions.

    5.6k GitHub starsUsed in 2 repos~4.2k tokens
    Auto-check passed

Categories

Questions about Use JS Interop

What does Use JS Interop do?

Add, review, or fix JavaScript interop in Blazor components. Use JS Interop is an agent skill from dotnet/skills, published by the product's own GitHub organization. Add, review, or fix JavaScript interop in Blazor components.

When should I use Use JS Interop?

Use JS Interop fits situations like: : calling JavaScript from Blazor; calling .NET from JavaScript; collocated .razor.js modules; IJSObjectReference lifecycle.

How do I install Use JS Interop in Claude Code?

Run `npx skills add dotnet/skills --skill use-js-interop -a claude-code`. Or copy the skill folder (plugins/dotnet-blazor/skills/use-js-interop in dotnet/skills) into .claude/skills/use-js-interop in your project. Claude Code loads it when a task matches its description.

How do I install Use JS Interop in Codex?

Run `npx skills add dotnet/skills --skill use-js-interop -a codex`. Or copy the skill folder (plugins/dotnet-blazor/skills/use-js-interop in dotnet/skills) into .agents/skills/use-js-interop in your project. Codex loads it when a task matches its description.

Can I use Use JS Interop in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add dotnet/skills --skill use-js-interop -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/use-js-interop, .gemini/skills/use-js-interop, .github/skills/use-js-interop and .opencode/skills/use-js-interop in your project.

What does Use JS Interop need to run?

SKILL.md names no scripts, command-line tools or credentials: Use JS Interop is instructions for the agent only.

Does Use JS Interop access the network?

SKILL.md contains no URLs. Any network use would come from the scripts or tools the agent runs. This is read from the text; nothing was executed.

Is Use JS Interop safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Use JS Interop use?

Use JS Interop is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Use JS Interop use?

About 2.7k tokens (SKILL.md is roughly 11k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full.

What are the alternatives to Use JS Interop?

Skills that share tags, products or a category with Use JS Interop: C# and .NET Developer (Jeffallan/claude-skills, 12k stars), Blazor (managedcode/dotnet-skills, 486 stars), Dotnet Backend Patterns (wshobson/agents, 40k stars) and Using Dotnet (novotnyllc/dotnet-artisan, 233 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Use JS Interop?

dotnet (a GitHub organization, an official publisher) maintains it in dotnet/skills, which has 5,568 GitHub stars. The repository holds 91 skills in this directory. The repository was last updated on October 7, 2026.

Source: dotnet/skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.