BlazeBridge 0.0.2
dotnet add package BlazeBridge --version 0.0.2
NuGet\Install-Package BlazeBridge -Version 0.0.2
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BlazeBridge" Version="0.0.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BlazeBridge" Version="0.0.2" />
<PackageReference Include="BlazeBridge" />
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BlazeBridge --version 0.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
#r "nuget: BlazeBridge, 0.0.2"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BlazeBridge@0.0.2
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BlazeBridge&version=0.0.2
#tool nuget:?package=BlazeBridge&version=0.0.2
The NuGet Team does not provide support for this client. Please contact its maintainers for support.
BlazeBridge
Dynamic JavaScript interop for Blazor WebAssembly. Write JS interop code that looks and feels like native C#.
Installation
dotnet add package BlazeBridge
That's it! No setup required
Quick Start
@inject IJSRuntime JSRuntime
@code {
protected override async Task OnInitializedAsync()
{
await JS.Init(JSRuntime); // Call once at startup
}
void Demo()
{
dynamic js = JS.Global;
// Get/set properties
string title = js.document.title;
js.document.title = "New Title";
// Call methods
double random = js.Math.random();
js.console.log("Hello!");
}
async Task FetchDemo()
{
dynamic js = JS.Global;
var response = await js.fetch("https://api.example.com");
var data = await response.json();
}
}
Property Access
dynamic js = JS.Global;
// Get
string title = js.document.title;
double width = js.window.innerWidth;
string href = js.window.location.href;
// Set
js.document.title = "New Title";
js.localStorage["key"] = "value";
Method Calls
// All methods execute immediately - no .Eval() needed!
double random = js.Math.random();
double sqrt = js.Math.sqrt(144);
string json = js.JSON.stringify(new { x = 1, y = 2 });
// Void methods work too
js.console.log("Hello!");
js.alert("Alert!");
// DOM methods
var element = js.document.getElementById("myId");
var elements = js.document.querySelectorAll(".myClass");
Typed Results with .As<T>()
Use .As<T>() when you need a specific type:
// JS numbers are doubles - use .As<int>() to convert
int width = js.window.innerWidth.As<int>();
int count = js.myArray.length.As<int>();
// Get arrays with element type
int[] numbers = js.Array.from(new[] { 1, 2, 3 }).As<int[]>();
string[] names = js.Object.keys(obj).As<string[]>();
Promises (Async Operations)
For JS operations that return Promises (like fetch), just await:
// Fetch returns a Promise - just await it!
var response = await js.fetch("https://api.example.com/data");
var data = await response.json();
// Access properties
string name = data.name;
int id = data.id.As<int>();
Creating JS Objects
// Create new instances (after calling JS.Global once, JSRuntime is cached)
var date = JS.New("Date");
var regex = JS.New("RegExp", "\\d+", "g");
var map = JS.New("Map");
// Use the instance
string iso = date.toISOString();
map.set("key", "value");
Callbacks & Event Handlers
setTimeout / setInterval
// setTimeout
var callback = JS.Callback(() => {
Console.WriteLine("Timer fired!");
StateHasChanged();
});
js.setTimeout(callback, 1000);
// setInterval - IMPORTANT: clear interval BEFORE disposing callback!
int count = 0;
double intervalId = 0;
JSCallback? intervalCallback = null;
intervalCallback = JS.Callback(() => {
count++;
if (count >= 3) {
js.clearInterval(intervalId); // Clear FIRST
intervalCallback?.Dispose(); // Then dispose
}
StateHasChanged();
});
intervalId = js.setInterval(intervalCallback, 500).As<double>();
Event Listeners
var element = js.document.getElementById("myButton");
// JSDynamicCallback gives you a JSDynamic - access any property without serialization
var clickHandler = JS.JSDynamicCallback(e => {
Console.WriteLine($"Clicked at {e.clientX}, {e.clientY}");
Console.WriteLine($"Target: {e.target.id}");
Console.WriteLine($"Parent: {e.target.parentElement.tagName}"); // Works! No circular ref issues
StateHasChanged();
});
element.addEventListener("click", clickHandler);
// Cleanup when done
element.removeEventListener("click", clickHandler);
clickHandler.Dispose();
Typed Callbacks
var numbers = js.Array.from(new[] { 1, 2, 3 });
numbers.forEach(JS.Callback<int>(num => {
Console.WriteLine($"Number: {num}");
}));
DOM Manipulation
dynamic js = JS.Global;
// Get elements
var element = js.document.getElementById("myId");
// Modify content
element.textContent = "New text";
element.innerHTML = "<strong>Bold</strong>";
// Modify styles
element.setAttribute("style", "color: red;");
string bgColor = js.getComputedStyle(element).backgroundColor;
// Modify classes
element.classList.add("active");
element.classList.remove("inactive");
// Get dimensions
var rect = element.getBoundingClientRect();
double width = rect.width;
ES Module Imports
// After calling JS.Global once, you can omit JSRuntime
var module = JS.Import("./js/myModule.js");
var result = module.myFunction("arg1", 42);
string version = module.VERSION;
API Summary
| Operation | Syntax |
|---|---|
| Get property | string x = js.prop; |
| Set property | js.prop = value; |
| Call method | js.method(args); |
| Get typed | int x = js.prop.As<int>(); |
| Get array | int[] x = js.arr.As<int[]>(); |
| Index access | var x = js.arr[0]; |
| New object | var x = JS.New("Date"); |
| Import module | var m = JS.Import("./m.js"); |
| Await Promise | var x = await js.fetch(url); |
| Callback | JS.Callback(() => { }) |
| Dynamic callback | JS.JSDynamicCallback(e => e.target.id) |
Best Practices
- Use
.As<T>()for integers - JS numbers are doubles - Await Promises -
fetch,response.json(), etc. return Promises - Clear intervals before disposing - Always call
clearInterval()BEFORE disposing callbacks - Dispose callbacks - Always dispose
JSCallbackwhen done to prevent memory leaks - Cache references - Store
js.document.getElementById()results - Handle errors - Wrap interop calls in try-catch
License
MIT
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
-
net10.0
- Microsoft.AspNetCore.Components.Web (>= 10.0.2)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.