SpawnDev.BlazorJS 2.0.2

There is a newer version of this package available.
See the version list below for details.
dotnet add package SpawnDev.BlazorJS --version 2.0.2
NuGet\Install-Package SpawnDev.BlazorJS -Version 2.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="SpawnDev.BlazorJS" Version="2.0.2" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add SpawnDev.BlazorJS --version 2.0.2
#r "nuget: SpawnDev.BlazorJS, 2.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.
// Install SpawnDev.BlazorJS as a Cake Addin
#addin nuget:?package=SpawnDev.BlazorJS&version=2.0.2

// Install SpawnDev.BlazorJS as a Cake Tool
#tool nuget:?package=SpawnDev.BlazorJS&version=2.0.2

NuGet

Package Description Link
SpawnDev.BlazorJS Enhanced Blazor WebAssembly Javascript interop NuGet version
SpawnDev.BlazorJS.WebWorkers Blazor WebAssembly WebWorkers and SharedWebWorkers NuGet version

SpawnDev.BlazorJS

NuGet

An easy Javascript interop library designed specifically for client side Blazor.

Supports Blazor WebAssembly .Net 6, 7, and 8.

  • Use Javascript libraries in Blazor without writing any Javascript code
  • Alternative access to IJSRuntime JS is globally available without injection and is usable on the first line of Program.cs
  • Get and set global properties via JS.Set and JS.Get
  • Create new Javascript objects with JS.New
  • Get and set object properties via IJSInProcessObjectReference extended methods
  • Easily pass .Net methods to Javascript using the Callback.Create or Callback.CreateOne methods
  • Strongly typed Javascript object deserialization/serialization with interfaces
  • Strongly typed Javascript object deserialization/serialization with the JSObject base class
  • Over 100 strongly typed JSObject wrappers included in BlazorJS including Promises, WebGL, WEbRTC, DOM, etc...
  • Use SpawnDev.BlazorJS.WebWorkers to enable calling Blazor services in web worker threads

JS

// Get Set
var innerHeight = JS.Get<int>("window.innerHeight");
JS.Set("document.title", "Hello World!");

// Call
var item = JS.Call<string?>("localStorage.getItem", "itemName");
JS.CallVoid("addEventListener", "resize", Callback.Create(() => Console.WriteLine("WindowResized"), _callBacks));

IJSInProcessObjectReference extended

// Get Set
var window = JS.Get<IJSInProcessObjectReference>("window");
window.Set("myVar", 5);
var myVar = window.Get<int>("myVar");

// Call
window.CallVoid("addEventListener", "resize", Callback.Create(() => Console.WriteLine("WindowResized")));

Create a new Javascript object

var worker = JS.New("Worker", myWorkerScript);

Callback

Pass methods to Javascript using the Callback.Create and Callback.CreateOne methods. These methods use type arguments to set the types expected for incoming arguments (if any) and the expected return type (if any.) async methods are passed as Promises.

Pass lambda callbacks to Javascript

JS.Set("testCallback", Callback.Create<string>((strArg) => {
    Console.WriteLine($"Javascript sent: {strArg}");
    // this prints "Hello callback!"
}));
// in Javascript
testCallback('Hello callback!');

Pass method callbacks to Javascript

string SomeNetFn(string input){
    return $"Recvd: {input}";
}

JS.Set("someNetFn", Callback.CreateOne<string, string>(SomeNetFn));
// in Javascript
someNetFn('Hello callback!');

// prints
Recvd: Hello callback!

Pass async method callbacks to Javascript Under the hood, BlazorJS is returning a Promise to Javascript when the method is called

async Task<string> SomeNetFnAsync(string input){
    return $"Recvd: {input}";
}

JS.Set("someNetFnAsync", Callback.CreateOne<string, string>(SomeNetFnAsync));
// in Javascript
await someNetFnAsync('Hello callback!');

// prints
Recvd: Hello callback!

IJSObject Interface

SpawnDev.BlazorJS can now wrap Javascript objects using interfaces. Just like objects derived from the JSObject class, IJSObject interfaces internally use IJSInProcessObjectReference to wrap a Javascript object for direct manipulation and can be passed to and from Javascript. The main difference is IJSObjects use DispatchProxy to implement the desired interface at runtime instead of requiring a type that inherits JSObject. Currently SpawnDev.BlazorJS does not provide any interfaces for Javascript objects or apis but interfaces are simple to set up.

IJSObject Example

// create an interface for your Javascript object that implements IJSObject
public interface IWindow : IJSObject 
{
    string Name { get; set; }
    void Alert(string msg = "");
    // ...
}

// use your IJSObject interface to interact with the Javascript object
public void IJSObjectInterfaceTest() {
    var w = JS.Get<IWindow>("window");
    var randName = Guid.NewGuid().ToString();
    // directly set the window.name property
    w.Name = randName;
    // verify the read back
    if (w.Name != randName) throw new Exception("Interface property set/get failed");
}

JSObject Base Class

JSObjects are wrappers around IJSInProcessReference objects that can be passed to and from Javascript and allow strongly typed access to the underlying object. JSObjects take a bit more work to set up but offer more versatility.

JSObject type wrapper example (same as the IJSObject interface example above but with JSObject)

// create a class for your Javascript object that inherits from JSObject
public class Window : JSObject 
{
    public string Name { get => JSRef.Get<string>("name"); set => JSRef.Set("name", value); }
    public void Alert(string msg = "") => JSRef.CallVoid(msg);
    // ...
}

// use the JSObject class to interact with the Javascript object
public void JSObjectClassTest() {
    var w = JS.Get<Window>("window");
    var randName = Guid.NewGuid().ToString();
    // directly set the window.name property
    w.Name = randName;
    // verify the read back
    if (w.Name != randName) throw new Exception("Interface property set/get failed");
}

Use the extended functions of IJSInProcessObjectReference to work with Javascript objects or use the growing library of over 100 of the most common Javascript objects, including ones for Window, HTMLDocument, WebStorage (localStorage and sessionStorage), WebGL, WebRTC, and more in SpawnDev.BlazorJS.JSObjects. JSObjects are wrappers around IJSInProcessObjectReference that allow strongly typed use.

Below shows a section of the SpawnDev.BlazorJS.JSObjects.Window class. Window's base type, EventTarget, inherits from JSObject.

public class Window : EventTarget {
    // all JSObject types must have this constructor
    public Window(IJSInProcessObjectReference _ref) : base(_ref) { }
    // here is a property with both getter and setter
    public string? Name { get => JSRef.Get<string>("name"); set => JSRef.Set("name", value); }
    // here is a read only property that returns another JSObject type
    public WebStorage LocalStorage => JSRef.Get<WebStorage>("localStorage");
    // here are methods
    public long SetTimeout(Callback callback, double delay) => JSRef.Call<long>("setTimeout", callback, delay);
    public void ClearTimeout(long requestId) => JSRef.CallVoid("clearTimeout", requestId);    
    // ... 
}

Below the JSObject derived Window class is used

// below the JSObject derived Window class is used
using var window = JS.Get<Window>("window");
var randName = Guid.NewGuid().ToString();
// set and get properties
window.Name = randName;
var name = window.Name;
// call methods
window.Alert("Hello!");

Promise

SpawnDev.BlazorJS.JSObjects.Promise - is a JSObject wrapper for the Javascript Promise class. Promises can be created in .Net to wrap async methods or Tasks. They are essentially Javascript's version of Task.

Ways to create a Promise in .Net

var promise = new Promise();
// pass to Javascript api
...
// then later resolve
promise.Resolve();

Create Promise from lambda

var promise = new Promise(async () => {
    await Task.Delay(5000);
});
// pass to Javascript api

Create Promise from lambda with return value

var promise = new Promise<string>(async () => {
    await Task.Delay(5000);
    return "Hello world!";
});
// pass to Javascript api

Create Promise from Task

var taskSource = new TaskCompletionSource<string>();
var promise = new Promise<string>(taskSource.Task);
// pass to Javascript api
...
// then later resolve
taskSource.TrySetResult("Hello world!");

Below is a an example that uses Promises to utilize the Web Locks API

using var navigator = JS.Get<Navigator>("navigator");
using var locks = navigator.Locks;

Console.WriteLine($"lock: 1");

using var waitLock = locks.Request("my_lock", Callback.CreateOne((Lock lockObj) => new Promise(async () => {
    Console.WriteLine($"lock acquired 3");
    await Task.Delay(5000);
    Console.WriteLine($"lock released 4");
})));

using var waitLock2 = locks.Request("my_lock", Callback.CreateOne((Lock lockObj) => new Promise(async () => {
    Console.WriteLine($"lock acquired 5");
    await Task.Delay(5000);
    Console.WriteLine($"lock released 6");
})));

Console.WriteLine($"lock: 2");

Undefinable<T> Passing undefined to Javascript

Some Javascript API calls may have optional parameters that behave differently depending on if you pass a null versus undefined. You can now retain string typing on JSObject method calls and support passing undefined for JSObject parameters.

New Undefinable<T> type.

Example from Test app unit tests

// an example method with a parameter that can also be null or undefined
// T of Undefinable<T> must be nullable
void MethodWithUndefinableParams(string varName, Undefinable<bool?>? window)
{
    JS.Set(varName, window);
}

bool? w = false;
// test to show the value is passed normally
MethodWithUndefinableParams("_willBeDefined2", w);
bool? r = JS.Get<bool?>("_willBeDefined2");
if (r != w) throw new Exception("Unexpected result");

w = null;
// null defaults to passing as undefined
MethodWithUndefinableParams("_willBeUndefined2", w);
if (!JS.IsUndefined("_willBeUndefined2")) throw new Exception("Unexpected result");

// if you need to pass null to an Undefinable parameter use Undefinable<T?>.Null
MethodWithUndefinableParams("_willBeNull2", Undefinable<bool?>.Null);
if (JS.IsUndefined("_willBeNull2")) throw new Exception("Unexpected result");

// another way to pass undefined
MethodWithUndefinableParams("_willAlsoBeUndefined2", Undefinable<bool?>.Undefined);
if (!JS.IsUndefined("_willAlsoBeUndefined2")) throw new Exception("Unexpected result");

If using JSObjects you can also use JSObject.Undefined<T> to create an instance that will be passed to Javascript as undefined.

// Create an instance of the Window JSObject class that is revived in Javascript as undefined
var undefinedWindow = JSObject.Undefined<Window>();
// undefinedWindow is an instance of Window that is revived in Javascript as undefined
JS.Set("_undefinedWindow", undefinedWindow);
var isUndefined = JS.IsUndefined("_undefinedWindow");
// isUndefined == true here

Custom JSObjects

Implement your own JSObject classes for Javascript objects not already available in the BlazorJS.JSObjects library.

Instead of this (simple but not as reusable)

var audio = JS.New("Audio", "https://some_audio_online");
audio.CallVoid("play");

You can do this...
Create a custom JSObject wrapper

public class Audio : JSObject
{
    public Audio(IJSInProcessObjectReference _ref) : base(_ref) { }
    public Audio(string url) : base(JS.New("Audio", url)) { }
    public void Play() => JSRef.CallVoid("play");
}

Then use your new object

var audio = new Audio("https://some_audio_online");
audio.Play();

SpawnDev.BlazorJS.WebWorkers

NuGet

  • Easily call Blazor Services in separate threads with WebWorkers and SharedWebWorkers

  • Does not require SharedArrayBuffer and therefore does not require the special HTTP headers associated with using it.

  • Supports and uses transferable objects whenever possible

  • Works in Blazor WASM .Net 6, 7, and 8.

  • Tested on (with .Net 8):
    Chrome Windows - Working
    MS Edge Windows - Working
    Firefox Windows - Working
    Chrome Android - Working
    MS Edge Android - Working
    Firefox Android - Working

Firefox WebWorkers note:
Firefox does not support dynamic modules in workers, which originally made BlazorJS.WebWorkers fail in that browser. The web worker script now tries to detect this and changes the blazor wasm scripts before they are loaded to workaround this limitation. It is possible some other browsers may have this issue but may not be detected properly.

Issues can be reported here on GitHub.

Example WebWorkerService setup and usage

// Program.cs
...
using SpawnDev.BlazorJS;
using SpawnDev.BlazorJS.WebWorkers;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
if (JS.IsWindow)
{
    // we can skip adding dom objects in non UI threads
    builder.RootComponents.Add<App>("#app");
    builder.RootComponents.Add<HeadOutlet>("head::after");
}
// add services
builder.Services.AddSingleton((sp) => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
// SpawnDev.BlazorJS.WebWorkers
builder.Services.AddSingleton<WebWorkerService>();
// app specific services...
// worker services should be registered with an interface to work with WebWorker.GetService<TServiceInterface>()
builder.Services.AddSingleton<IMathsService, MathsService>();
// build 
WebAssemblyHost host = builder.Build();
// init WebWorkerService 
var workerService = host.Services.GetRequiredService<WebWorkerService>();
await workerService.InitAsync();
await host.RunAsync();

WebWorker


// Create a WebWorker
var webWorker = await workerService.GetWebWorker();

// Call GetService<ServiceInterface> on a web worker to get a proxy for the service on the web worker.
// GetService can only be called with Interface types
var workerMathService = webWorker.GetService<IMathsService>();

// Call async methods on your worker service
var result = await workerMathService.CalculatePi(piDecimalPlaces);

// Action types can be passed for progress reporting
var result = await workerMathService.CalculatePiWithActionProgress(piDecimalPlaces, new Action<int>((i) =>
{
    // the worker thread can call this method to report progress if desired
    piProgress = i;
    StateHasChanged();
}));

SharedWebWorker

Calling GetSharedWebWorker in another window with the same sharedWorkerName will return the same SharedWebWorker

// Create or get SHaredWebWorker with the provided sharedWorkerName
var sharedWebWorker = await workerService.GetSharedWebWorker("workername");

// Just like WebWorker but shared
var workerMathService = sharedWebWorker.GetService<IMathsService>();

// Call async methods on your shared worker service
var result = await workerMathService.CalculatePi(piDecimalPlaces);

Send events

// Optionally listen for event messages
worker.OnMessage += (sender, msg) =>
{
    if (msg.TargetName == "progress")
    {
        PiProgress msgData = msg.GetData<PiProgress>();
        piProgress = msgData.Progress;
        StateHasChanged();
    }
};

// From SharedWebWorker or WebWorker threads send an event to connected parents
workerService.SendEventToParents("progress", new PiProgress { Progress = piProgress });

// Or on send an event to a connected worker
webWorker.SendEvent("progress", new PiProgress { Progress = piProgress });

Worker Transferable JSObjects

Faster is better. SpawnDev WebWorkers use transferable objects by default for better performance, but it can be disabled with WorkerTransferAttribute. Setting WorkerTransfer to false will cause the property, return value, or parameter to be copied to the receiving thread instead of transferred.

Example

public class ProcessFrameResult : IDisposable
{
    [WorkerTransfer(false)]
    public ArrayBuffer? ArrayBuffer { get; set; }
    public byte[]? HomographyBytes { get; set; }
    public void Dispose(){
        ArrayBuffer?.Dispose();
    }
}

[return: WorkerTransfer(false)]
public async Task<ProcessFrameResult?> ProcessFrame([WorkerTransfer(false)] ArrayBuffer? frameBuffer, int width, int height, int _canny0, int _canny1, double _needlePatternSize)
{
    var ret = new ProcessFrameResult();
    // ...
    return ret;
}

In the above example; the WorkerTransferAttribute on the return type set to false will prevent all properties of the return type from being transferred.

Transferable JSObject types

ArrayBuffer
MessagePort
ReadableStream
WritableStream
TransformStream
AudioData
ImageBitmap
VideoFrame
OffscreenCanvas
RTCDataChannel

IDisposable

NOTE: The above code shows quick examples. Some objects implement IDisposable, such as JSObject, Callback, and IJSInProcessObjectReference types.

JSObject types will dispose of their IJSInProcessObjectReference object when their finalizer is called if not previously disposed.

Callback types must be disposed unless created with the Callback.CreateOne method, in which case they will dispose themselves after the first callback. Disposing a Callback prevents it from being called.

IJSInProcessObjectReference does not dispose of interop resources with a finalizer and MUST be disposed when no longer needed. Failing to dispose these will cause memory leaks.

IDisposable objects returned from a WebWorker or SharedWorker service are automatically disposed after the data has been sent to the calling thread.

Support

Issues can be reported here on GitHub.

Inspired by Tewr's BlazorWorker implementation. Thank you! I wrote my implementation from scratch as I needed workers in .Net 7.
https://github.com/Tewr/BlazorWorker

BlazorJS and WebWorkers Demo
https://blazorjs.spawndev.com/

Buy me a coffee

paypal

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (5)

Showing the top 5 NuGet packages that depend on SpawnDev.BlazorJS:

Package Downloads
SpawnDev.BlazorJS.WebWorkers

Easily call Services in separate threads with WebWorkers and SharedWebWorkers. Run Blazor WASM in the ServiceWorker.

SpawnDev.BlazorJS.FFmpegWasm

SpawnDev.BlazorJS.FFmpegWasm is a Blazor WASM wrapper around ffmpeg.wasm and contains only the base ffmpeg.js and 814.ffmpeg.js files.

SpawnDev.BlazorJS.WebTorrents

WebTorrents in Blazor WebAssembly

SpawnDev.BlazorJS.BabylonJS6

Brings BabylonJS 6 to Blazor WASM.

SpawnDev.BlazorJS.VisNetwork

VisNetwork in Blazor WebAssembly

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
2.2.67 104 3/27/2024
2.2.66 116 3/24/2024
2.2.65 91 3/21/2024
2.2.64 144 3/11/2024
2.2.63 117 3/9/2024
2.2.62 86 3/7/2024
2.2.61 91 3/6/2024
2.2.60 95 3/6/2024
2.2.58 146 3/2/2024
2.2.57 179 2/24/2024
2.2.56 137 2/18/2024
2.2.55 90 2/17/2024
2.2.53 92 2/15/2024
2.2.52 96 2/15/2024
2.2.51 84 2/15/2024
2.2.50 85 2/13/2024
2.2.49 256 2/2/2024
2.2.48 531 12/29/2023
2.2.47 140 12/20/2023
2.2.46 165 12/15/2023
2.2.45 96 12/10/2023
2.2.44 88 12/10/2023
2.2.42 105 12/9/2023
2.2.41 120 12/9/2023
2.2.40 89 12/8/2023
2.2.38 519 11/21/2023
2.2.37 150 11/16/2023
2.2.36 79 11/16/2023
2.2.35 106 11/14/2023
2.2.34 95 11/13/2023
2.2.33 67 11/10/2023
2.2.32 79 11/10/2023
2.2.31 66 11/9/2023
2.2.28 81 11/7/2023
2.2.27 136 10/31/2023
2.2.26 193 10/22/2023
2.2.25 87 10/20/2023
2.2.24 75 10/20/2023
2.2.23 79 10/20/2023
2.2.22 74 10/20/2023
2.2.21 75 10/20/2023
2.2.20 76 10/19/2023
2.2.19 70 10/19/2023
2.2.18 72 10/19/2023
2.2.17 171 10/13/2023
2.2.16 461 10/12/2023
2.2.15 73 10/12/2023
2.2.14 117 10/5/2023
2.2.13 94 10/5/2023
2.2.12 72 10/5/2023
2.2.11 180 10/3/2023
2.2.10 199 9/18/2023
2.2.9 71 9/18/2023
2.2.8 250 9/14/2023
2.2.7 84 9/13/2023
2.2.6 2,954 9/6/2023
2.2.5 115 8/30/2023
2.2.4 143 8/26/2023
2.2.3 103 8/20/2023
2.2.2 92 8/18/2023
2.2.1 100 8/11/2023
2.2.0 182 7/17/2023
2.1.15 109 5/26/2023
2.1.14 92 5/20/2023
2.1.13 108 4/26/2023
2.1.12 160 4/21/2023
2.1.11 91 4/19/2023
2.1.10 103 4/19/2023
2.1.8 133 4/10/2023
2.1.7 154 3/27/2023
2.1.6 143 3/24/2023
2.1.5 122 3/23/2023
2.1.4 114 3/23/2023
2.1.3 122 3/23/2023
2.1.2 127 3/21/2023
2.1.0 120 3/21/2023
2.0.3 125 3/21/2023
2.0.2 124 3/20/2023
2.0.1 128 3/20/2023
2.0.0 127 3/20/2023
1.9.2 134 3/14/2023
1.8.1 122 3/11/2023
1.8.0 118 3/10/2023
1.7.1 120 3/10/2023
1.7.0 119 3/8/2023
1.6.4 134 3/1/2023
1.6.3 321 1/31/2023
1.6.2 336 1/24/2023
1.6.1 361 1/11/2023
1.6.0 357 1/11/2023
1.5.0 408 12/23/2022
1.4.0 363 12/20/2022
1.3.0 358 12/16/2022
1.2.7 318 12/16/2022
1.2.5 319 12/14/2022
1.2.4.1 315 12/13/2022
1.2.4 313 12/13/2022
1.2.3 317 12/13/2022
1.2.1 305 12/10/2022
1.2.0 301 12/10/2022
1.1.0 296 12/6/2022
1.0.0 299 12/6/2022