본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)5.8k · #14570

use-js-interop

하는 일

이 스킬은 Blazor 컴포넌트에서 JavaScript를 호출하고, JavaScript에서 .NET 코드를 호출하는 방법을 안내합니다. Blazor 페이지 안에서 차트 라이브러리나 캔버스처럼 브라우저 기능이 필요한 .NET 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓Blazor 컴포넌트에 차트나 지도 같은 JavaScript 라이브러리가 필요할 때.
  • ✓JavaScript가 Blazor 컴포넌트를 다시 호출해야 할 때.
  • ✓컴포넌트가 제거된 뒤 JavaScript 참조에서 오류나 누수가 생길 때.

스킬 링크

https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

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.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“작은 JavaScript 모듈을 이용해 제 Blazor 페이지에 캔버스 차트를 추가하고, 컴포넌트가 그 모듈을 호출하게 해 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트가 컴포넌트 옆에 JavaScript 모듈을 두고, 페이지가 렌더링된 뒤에만 호출하며, 컴포넌트가 제거될 때 참조를 정리합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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
자주 묻는 질문

서버 사전 렌더링 중에 JavaScript를 실행할 수 있나요?

아니요. JavaScript는 사전 렌더링 중에 쓸 수 없으므로, 이 스킬은 렌더링 뒤에만 JavaScript를 호출하도록 합니다.

전역 스크립트를 쓰나요?

아니요. 전역 script 태그 대신 함수를 내보내는 같은 위치의 모듈을 사용합니다.

정리 작업은 어떻게 하나요?

컴포넌트가 제거될 때 JavaScript 참조를 해제하는 작업을 다룹니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
5.8k
순위
#14570
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬