Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blazor onended is not firing

I'm starting to work with Blazor. My intention is playing one random Video after another. Therefore i wanted to use the Blazor Event Listener. But the onended Event is not firing (everything is working fine with onclick).

video Element:

<figure id="video-player">
    <video autoplay="autoplay" @onended="NewVideo">
        @videoUrl
    </video>
</figure>

Codeblock:

private MarkupString videoUrl;

    protected override void OnInitialized()
    {
        NewVideo();
    }

    private void NewVideo()
    {
        videoUrl = new MarkupString($"<source src=\"videos/{tv.GetRandomVideoFileName()}\" type=\"video/mp4\">");

    }

OnInitialized is working as intended, and if I change the onended to onclick everything is also working fine.

To Mention: I know, only changing the source wouldnt start the next Video. That would be my next Task on the List :). First I only want to Change the source in the DOM.

like image 433
SvenMind Avatar asked Oct 26 '25 06:10

SvenMind


1 Answers

The short story is that this isn't supported, and did not make the v5 release. See the issue here:

https://github.com/dotnet/aspnetcore/issues/24323

The longer story is that you'll have to fire up some JS interop. Reference is here: https://learn.microsoft.com/en-us/aspnet/core/blazor/call-dotnet-from-javascript?view=aspnetcore-5.0#component-instance-method-call

On the JS side, you'll need something like this:

var player = document.getElementById('player');
player.onended = (e) => {
    DotNet.invokeMethodAsync('{assembly_name_here}', 'SongEnded');
};

The assembly name is probably the name of the project, like MyBlazorApp. Then in your component, you'll need a static action to get the thing wired up:

    protected override void OnInitialized()
    {
        action = UpdateMessage;
    }
    private static Action action;

    private void UpdateMessage()
    {
        // DO STUFF HERE
    }

    [JSInvokable]
    public static void SongEnded()
    {
        action.Invoke();
    }

It's a little clunky, sure, but essentially you're mapping a JS event to a static method on the component. You're probably thinking, "Well, what if I have multiple instances of the component?" In that case, you'll have to be a little creative about passing context to the static method and finding the right instance. Again, check the reference above, it has plenty of examples.

like image 173
Jeff Putz Avatar answered Oct 29 '25 08:10

Jeff Putz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!