You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
SpawnJSRuntime is the central interop singleton that provides synchronous and asynchronous access to the JavaScript environment from Blazor WebAssembly. It wraps the IJSInProcessRuntime and adds typed property access, method invocation, object construction, scope detection, and module loading. All property paths support dot notation and null-conditional (?.) syntax. This is the primary entry point for all JS interop in SpawnDev.SpawnJS - never use IJSRuntime or IJSInProcessRuntime directly.
Setup
Register and start the runtime in Program.cs:
builder.Services.AddSpawnJSRuntime();awaitbuilder.Build().SpawnJSRunAsync();// NOT RunAsync()
Accessing the Runtime
// Via dependency injection (preferred)[Inject]SpawnJSRuntimeJS{get;set;}// Via static property on SpawnJSObjectSpawnJSRuntime js = SpawnJSObject.JS;// Via static property on SpawnJSRuntime itself
SpawnJSRuntime js = SpawnJSRuntime.JS;
Properties
Property
Type
Description
JS
SpawnJSRuntime
Static singleton instance. Accessible from anywhere.
GlobalThis
SpawnJSObject?
The globalThis SpawnJSObject instance for the current scope.
WindowThis
Window?
If globalThis is a Window, refers to globalThis; otherwise null.
DedicateWorkerThis
DedicatedWorkerGlobalScope?
If globalThis is a DedicatedWorkerGlobalScope; otherwise null.
SharedWorkerThis
SharedWorkerGlobalScope?
If globalThis is a SharedWorkerGlobalScope; otherwise null.
ServiceWorkerThis
ServiceWorkerGlobalScope?
If globalThis is a ServiceWorkerGlobalScope; otherwise null.
GlobalThisTypeName
string
The constructor.name of globalThis (e.g., "Window", "DedicatedWorkerGlobalScope").
GlobalScope
GlobalScope
Enum value representing the current scope type.
IsWindow
bool
True if globalThis is a Window.
IsWorker
bool
True if globalThis is any worker (Dedicated, Shared, or Service).
IsDedicatedWorkerGlobalScope
bool
True if globalThis is a DedicatedWorkerGlobalScope.
IsSharedWorkerGlobalScope
bool
True if globalThis is a SharedWorkerGlobalScope.
IsServiceWorkerGlobalScope
bool
True if globalThis is a ServiceWorkerGlobalScope.
IsBrowser
bool
True if running in a browser (OperatingSystem.IsBrowser()).
HasInProcessRuntime
bool
True if the in-process JS runtime is available.
CrossOriginIsolated
bool?
Whether the site is in a cross-origin isolated state (COOP/COEP).
InstanceId
string
Unique hex instance ID generated at startup.
ReadyTime
double
Milliseconds elapsed until all background services started.
EnvironmentVersion
string
The .NET Environment.Version string.
FrameworkVersion
string
The .NET runtime framework description (version number).
InformationalVersion
string
The SpawnJSRuntime assembly informational version.
FileVersion
string
The SpawnJSRuntime assembly file version.
Methods - Property Access
Method
Return Type
Description
Get<T>(string key)
T
Get a global property value. Supports dot notation and ?. null-conditional.
Get(Type returnType, string key)
object?
Get a global property value as the specified Type.
GetAsync<T>(string key)
Task<T>
Get a global property value that returns a Promise.
Set(string key, object? value)
void
Set a global property value. Supports dot notation.
Delete(string key)
bool
Delete a global property.
In(string key)
bool
Returns true if the key exists in globalThis (key in target).
Keys(bool hasOwnProperty = false)
List<string>
Returns property string keys of globalThis.
Keys(string key, bool hasOwnProperty = false)
List<string>
Returns property string keys of the target object at key.
Methods - Type Checking
Method
Return Type
Description
TypeOf(string key)
string
Returns the typeof result ("object", "function", "undefined", etc.).
IsUndefined(string key)
bool
Returns true if typeof key === "undefined".
ConstructorName()
string?
Returns the constructor.name of globalThis.
ConstructorName(string key)
string?
Returns the constructor.name of the target at key.
ConstructorNames()
string[]
Returns constructor names from the entire prototype chain of globalThis.
ConstructorNames(string key)
string[]
Returns constructor names from the entire prototype chain at key.
JSEquals(string key, object? obj2, bool full = false)
Load a script only if the specified global variable is undefined.
LoadScripts(string[] sources)
Task
Load multiple scripts in parallel.
Import(string moduleName)
Task<ModuleNamespaceObject>
Dynamic ES module import (import()).
Import(string name, string moduleName)
Task<ModuleNamespaceObject>
Import and assign to a global variable.
Import<T>(string moduleName)
Task<T>
Dynamic import returning a typed module.
Import<T>(string name, string moduleName)
Task<T>
Import as typed and assign to global variable.
Methods - Convenience
Method
Return Type
Description
Log(params object?[] args)
void
Write to console.log.
LogError(params object?[] args)
void
Write to console.error.
LogWarn(params object?[] args)
void
Write to console.warn.
Fetch(string resource)
Task<Response>
Call the Fetch API.
Fetch(string resource, FetchOptions options)
Task<Response>
Call the Fetch API with options.
Fetch(Request resource)
Task<Response>
Call the Fetch API with a Request object.
SetTimeout(Action callback, int msDelay)
void
Call setTimeout with a .NET Action (auto-creates one-shot Callback).
SetTimeout(Callback callback, int msDelay)
void
Call setTimeout with an existing Callback.
GetWindow()
Window?
Returns the window object or null.
GetDocument()
Document?
Returns the document object or null.
GetDocumentHead()
HTMLHeadElement?
Returns document.head or null.
GetDocumentBody()
HTMLBodyElement?
Returns document.body or null.
DocumentHeadAppendChild(Element element)
void
Append an element to document.head.
DocumentBodyAppendChild(Element element)
void
Append an element to document.body.
DocumentCreateElement<T>(string elementType)
T
Create a DOM element of the specified type.
ReturnMe<T>(object? obj)
T
Re-import an object from JS as the specified type.
ToJSRef(ElementReference elementRef)
SpawnJSObjectReference
Convert a Blazor ElementReference to a JSRef.
IsScope(GlobalScope scope)
bool
Returns true if the current scope matches the supplied GlobalScope flag.
IsDisplayModeStandalone()
bool
Returns true if running as a standalone PWA.
Example - Basic Property Access
@injectSpawnJSRuntimeJS// Read global properties with dot notationvar height =JS.Get<int>("window.innerHeight");varuserAgent=JS.Get<string>("navigator.userAgent");// Null-conditional paths - returns null instead of throwingvarsize=JS.Get<int?>("fruit.options?.size");// Set global propertiesJS.Set("myApp.config.debug",true);// Check typesboolisUndef=JS.IsUndefined("someVar");stringjsType=JS.TypeOf("document");// "object"stringctorName=JS.ConstructorName("document");// "HTMLDocument"
if(JS.IsWindow){// Running in the main browser windowvardoc=JS.WindowThis!.Document;}elseif(JS.IsDedicatedWorkerGlobalScope){// Running in a dedicated web workerJS.DedicateWorkerThis!.PostMessage("worker ready");}elseif(JS.IsServiceWorkerGlobalScope){// Running in a service worker}
Example - Module Loading
// Dynamic ES module importusingvarmodule=awaitJS.Import("https://cdn.example.com/lib.js");// Import and assign to a global variable (cached on subsequent calls)usingvaracorn=awaitJS.Import("acorn","https://cdn.jsdelivr.net/npm/acorn/+esm");