BlazorJS is a small package to have better interaction with JavaScript.
- Use a Scripts Component on every page or component to load JavaScript or Stylesheet files when not loaded, and unload automatically on dispose if you want to.
- This library provides extensions for IJSRuntime for dynamic invocation that eliminates the requirement to create JS wrapping functions for everything
- A possibility to hook events on a Blazor component or page.
- Import a module and create a JS object reference from it
Add the nuget Package BlazorJS
to your blazor project
Open _Imports.razor
from your project and add using for BlazorJS
...
@using BlazorJS
The scripts component allows you to include every javascipt file easily to your pages or components.
For example open any page like the index.razor
and add
<Scripts src="js/myjsfile.js"></Scripts>
This component can also load stylesheet files
<Scripts src="js/myjsfile.js,css/mystyle.css"></Scripts>
Multiple js files can be loaded with a comma seperator ,
<Scripts src="js/myjsfile.js, js/myjsfile2.js"></Scripts>
The Dynamic Invocation extension for IJSRuntime allows for dynamic invocation of JavaScript functions from C#. This extension provides a single method, DInvokeVoidAsync, which takes in two arguments: a function to be invoked and an array of objects to be passed as arguments to that function.
Usage
The DInvokeVoidAsync
method can be called on any instance of IJSRuntime, and takes in general two arguments: a function to be invoked and an array of objects to be passed as arguments to that function.
Here are some examples of how the method can be used:
await jsRuntime.DInvokeVoidAsync(window => window.alert("test"));
if in your scope a variable is available. (In the base Blazor Sample the currentCount for example) Something like this is not enough
// DONT COPY THIS!! SAMPLE FOR NOT WORKING
await jsRuntime.DInvokeVoidAsync(window => window.alert(currentCount));
await jsRuntime.DInvokeVoidAsync((window, c) => window.alert(c), currentCount);
await jsRuntime.DInvokeVoidAsync((window, c, p2, p3..) => window.alert(c), currentCount, param2, param3, ...);
await jsRuntime.DInvokeVoidAsync((window, c, x) =>
{
window.alert(c);
window.console.log(x);
}, currentCount, "Flo");
await jsRuntime.DInvokeVoidAsync(window => window.alert(currentCount), JSArgument.For(currentCount).ToArray());
await jsRuntime.DInvokeVoidAsync(window => window.alert(currentCount + " - " + date + name), JSArgument.For(currentCount).And(date).And(name));
var date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
var name = "John";
await jsRuntime.DInvokeVoidAsync(window => window.alert(currentCount + " - " + date + name), JSArgument.For(currentCount).And(date).And(name));
All seen samples are also callable with an generic arg to use return values.
var res = await jsRuntime.DInvokeAsync<string>(window => window.prompt());
Console.WriteLine(res);
var hash = await jsRuntime.DInvokeAsync<string>(window =>
{
window.alert(currentCount);
return window.location.hash + "_" + currentCount;
}, new[] { JSArgument.For(currentCount) });
await jsRuntime.DInvokeVoidAsync(document => document.location.hash = hash, new[] { JSArgument.For(hash) });
// After alerting the currentCount we update the url in browser like this #1_2_3_4...
It is important to note that the function passed to DInvokeVoidAsync must be a lambda expression that takes in a dynamic and dynamic parameter.
Conclusion This extension provides a simple and easy way to invoke JavaScript functions from C# with support for dynamic arguments.
A simple possibility to hook events that should be extended more but currently supports an easy OnBlur extension for any element.
private BlazorJSEventInterop<PointerEventArgs> _jsEvent;
_jsEvent = new BlazorJSEventInterop<PointerEventArgs>(_jsRuntime);
await _jsEvent.OnBlur(OnFocusLeft, ".element-selector");
private Task OnFocusLeft(PointerEventArgs arg)
{
return Task.CompletedTask;
}
You can also use it manually with any event you want to.
private BlazorJSEventInterop<PointerEventArgs> _jsEvent;
_jsEvent = new BlazorJSEventInterop<PointerEventArgs>(_jsRuntime);
await _jsEvent.AddEventListener("NameOfEvent", async args => { await YourCallBack(); }, ".element-selector");
BlazorJs provides a small base component called BlazorJsBaseComponent<T>
to create a JS wrapper component.
This is a simple way to create a JS object reference from a module and use it in your blazor component.
- Create a razor component
YourComponent.razor
@inherits BlazorJs.BlazorJsBaseComponent<YourComponent>
<div @ref="ElementReference">
</div>
YourComponent.razor.cs
public partial class YourComponent
{
protected override string ComponentJsFile() => "./js/PathToYourComponent.js";
protected override string ComponentJsInitializeMethodName() => "initializeMethodForYourComponent";
[Parameter]
public string SomeGeneralParam { get; set; }
[Parameter, ForJs]
public int ParamForJs { get; set; } = 100;
[Parameter, ForJs("anotherParamForJsWithDifferentNameInJs")]
public int AnotherParamForJs { get; set; } = 100;
protected override async Task OnJsOptionsChanged()
{
// This method will automatically be called when a parameter marked with [ForJs] has changed
if (JsReference != null)
await JsReference.InvokeVoidAsync("setOptions", MyJsOptions());
}
private object MyJsOptions()
{
return this.AsJsObject(new
{
configValueWirthoutParam = 123,
});
}
/// <summary>
/// Gets the JavaScript arguments to pass to the component.
/// We override here because by default only the element reference abd dotnet reference is passed but we want to have directly the JsOptions available.
/// </summary>
public override object[] GetJsArguments() => new[] { ElementReference, CreateDotNetObjectReference(), MyJsOptions() };
}
- Create your js file thats located in the path you have defined in
ComponentJsFile()
in this case./js/PathToYourComponent.js
./js/PathToYourComponent.js
class YourComponent {
elementRef;
dotnet;
constructor(elementRef, dotNet, options) {
this.elementRef = elementRef;
this.dotnet = dotNet;
this.createWhatever(options);
}
createWhatever(options) {
// Do something with the options
console.log(options.paramForJs);
console.log(options.anotherParamForJsWithDifferentNameInJs);
console.log(options.configValueWirthoutParam);
}
setOptions(options) {
// Just update the options with the new ones
}
dispose() {
// Dispose everything you created
}
}
window.YourComponent = YourComponent;
// This method will be called from the BlazorJsBaseComponent and should match the name you have defined in `ComponentJsInitializeMethodName()`
export function initializeMethodForYourComponent(elementRef, dotnet, options) {
return new YourComponent(elementRef, dotnet, options);
}