Matas Vaitkevicius
Matas Vaitkevicius

Reputation: 61401

Blazor await JSRuntime.InvokeAsync<string> capturing image src in C# returns null when I can observe in JS value being captured

I am using Blazor to capture a frame from the camera as base64 encoded image

I have a weird issue when I place a breakpoint in JS code I can see image src being captured enter image description here

however, it never comes out of C# await JSRuntime.InvokeAsync<string> end. enter image description here

At this point, I feel like I am banging my head on the wall. Since the string is quite long I introduced a Timeout timespan of one minute, but that didn't help

My code:
Index.Razor

<div>
    <img id="captured-image" /> </div>

<div>
    <button @onclick="Save">Save</button> </div>


@code{

    int index = 0;

    protected override void OnInitialized()
    {
        index = localStorage.Length();
    }

    public async Task Save()
    {
        var src = await JSRuntime.InvokeAsync<string>("WebCamFunctions.getCapturedElement", new TimeSpan(0,1,0), new { capturedImageId = "captured-image" });

        localStorage.SetItem<string>((index + 1).ToString(), src);
    } }

m.js

window.WebCamFunctions = {
    getCapturedElement: (options) => { getCapturedElement(options); }
};

function getCapturedElement(options) {
    var base64EncodedImage = document.getElementById(options.capturedImageId).currentSrc;
    return base64EncodedImage;
}

Why is Blazor await JSRuntime.InvokeAsync<string> capturing image src in C# returns null when it gets the value in JS?

EDIT:

I tried capturing an empty image it is in JS src = '' it still is null var src = await JSRuntime.InvokeAsync<string> so probably it is not length related.

Upvotes: 1

Views: 2345

Answers (1)

JHBonarius
JHBonarius

Reputation: 11271

window.WebCamFunctions = {
    getCapturedElement: (options) => { getCapturedElement(options); }
};

That lambda doesn't return anything (or void ~= null). You need to return the return value

getCapturedElement: (options) => { return getCapturedElement(options); }

or shorter

getCapturedElement: (options) => getCapturedElement(options)

Easy to make a mistake like this. You could inline the function

window.WebCamFunctions = {
    getCapturedElement: function (options) {
       var base64EncodedImage = document.getElementById(options.capturedImageId).currentSrc;
       return base64EncodedImage;
    }
}

Upvotes: 3

Related Questions