use-js-interop
Fungsinya
Skill ini memandu pemanggilan JavaScript dari komponen Blazor dan pemanggilan kode .NET dari JavaScript. Skill ini untuk pengembang .NET yang membutuhkan fitur browser, seperti pustaka grafik atau canvas, di dalam halaman Blazor.
Kapan dipakai
- βSaat komponen Blazor membutuhkan pustaka JavaScript, misalnya grafik atau peta.
- βKetika JavaScript perlu memanggil kembali komponen Blazor.
- βKetika referensi JavaScript menyebabkan error atau kebocoran setelah komponen dihapus.
Link skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/use-js-interop/SKILL.mdSalin lalu tempelkan ke AI Anda (Claude, ChatGPT, atau Cursor) dan minta AI mengikuti instruksinya.
Cara pakai
Cara paling mudah: salin pesan ini dan tempelkan ke AI Anda. AI akan membaca skill dan mengikuti instruksinya.
Pesan siap tempel
Untuk Claude Code, Codex, atau Cursor: jalankan di folder proyek, lalu skill langsung terpasang.
Unduh SKILL.md lalu taruh di folder skill agen Anda.
Contoh permintaan ke AI
βTambahkan grafik canvas ke halaman Blazor saya menggunakan modul JavaScript kecil yang bisa dipanggil komponen.β
5 skill baru setiap minggu. 1 menit baca.
Cara kerjanya
Agent menempatkan modul JavaScript di samping komponen, memanggilnya hanya setelah halaman selesai dirender, dan membersihkan referensi saat komponen dihapus.
Konten teknis (SKILL.md asli)
Teks asli dari pembuat, dalam bahasa Inggris, langsung dari 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
Pertanyaan umum
Bisakah JavaScript berjalan saat prerendering di server?
Tidak. Skill ini menjaga pemanggilan JavaScript tetap setelah rendering, karena JavaScript tidak tersedia saat prerendering.
Apakah skill ini memakai skrip global?
Tidak. Skill ini memakai modul yang berdampingan dengan komponen dan fungsi yang diekspor, bukan tag skrip global.
Bagaimana dengan pembersihan?
Skill ini mencakup pembuangan referensi JavaScript saat komponen dihapus.
Detail
Deskripsi asli dari pembuat
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
Popularitas
- Bintang GitHub
- 5.8k
- Peringkat
- #14570
- Lisensi
- MIT
- Diperbarui
- 2/11/2026
Komentar
- β¦
Skill lain dari repositori ini
create-custom-agent
5.8kMembantu agent Anda membuat file agen kustom VS Code dengan alatnya sendiri, instruksi, dan serah terima ke agent lain.
create-skill
5.8kMembantu agent Anda membuat skill agent baru dengan nama yang valid, deskripsi pemicu yang jelas, dan file SKILL.md yang mengikuti standar.
csharp-scripts
5.8kMembantu agent Anda menjalankan program C# kecil sebagai satu file dengan alat baris perintah .NET, tanpa membuat proyek lengkap.
dotnet-pinvoke
5.8kMembantu agent Anda memanggil pustaka native C atau C++ dari .NET dengan benar, mencakup tanda tangan, penanganan string, memori, dan safe handle.
Skill serupa
angular-developer
280kMembantu agent Anda membuat kode Angular dan memberi saran struktur proyek. Berguna saat memulai proyek baru, membuat komponen, atau meningkatkan performa.
frontend-a11y
280kMembantu agent Anda membuat antarmuka web dapat diakses semua orang. Memastikan website dan aplikasi berfungsi baik dengan screen reader dan navigasi keyboard.
frontend-patterns
280kMembuat agent Anda menerapkan pola modern dalam frontend. Mengoptimalkan performa, mengelola state, dan mengikuti praktik terbaik React dan Next.js.