domblazorblazor-jsinterop

Calling methods upon DOM elements via JSInterop


How can I call a Javascript method of a (DOM) Element given a ElementReference (Blazor) parameter in a jsinterop (InvokeVoidAsync) call?

I guess I could assign an id attribute to that element and then pass document.getElementById("soandso").FunctionIWantToCall in my InvokeVoidAsync call, but that removes some of the usefulness of Blazor...


Solution

  • Nuget: SpawnDev.BlazorJS - 14,000+ downloads

    GitHub: SpawnDev.BlazorJS - examples and documentation.

    SpawnDev.BlazorJS allows full Blazor WebAssembly and Javascript interop without writing Javascript. The library has 280+ Javascript objects wrapped in C# classes for interacting directly with the DOM, WebRTC, Encryption, WebGL, etc. And instead of writing Javascript to make a Javascript library work in Blazor, you can create C# wrappers around the Javascript library objects. The number of features is too long to list here. I am always ready to help with any issues that you may come across (see Issues... 19 total, 0 open atm.)

    I am the author of SpawnDev.BlazorJS.

    C# example to access the DOM window:

    [Inject]
    BlazorJSRuntime JS { get; set; }
    
    void AttachEventHandlersExample()
    {
        using var window = JS.Get<Window>("window");
        // access properties
        window.LocalStorage.SetItem("myvar", "myvalue");
        // If this is the first time Window_OnStorage has been attached to an event a .Net reference is automatically created and held for future use and removal
        window.OnStorage += Window_OnStorage;
        // the window JSObject reference can safely be disposed as the .Net reference is attached to Window_OnStorage internally
    }
    void DetachEventHandlersExample()
    {
        using var window = JS.Get<Window>("window");
        // If this is the last reference of Window_OnStorage being removed then the .Net reference will automatically be disposed.
        // IMPORTANT - detaching is important for preventing resource leaks. .Net references are only released when the reference count reaches zero (same number of -= as += used)
        window.OnStorage -= Window_OnStorage;
    }
    
    void Window_OnStorage(StorageEvent storageEvent)
    {
        Console.WriteLine($"StorageEvent: {storageEvent.Key} has changed");
    }
    

    Using HTML elements via an ElementReference:

    var video = new HTMLVideoElement(elementReference);
    video.Src = "https://www.somesite.com/avideo.mp4";
    await video.Play();