I have a Blazor app built on .NET Core 3.1 and I need to be able to access USB port resources. I keep getting the error:
JavaScript interop calls cannot be issued at this time. This is because the component is being statically rendererd. When prerendering is enabled, JavaScript interop calls can only be performed during the OnAfterRenderAsync lifecycle method.
I have a pretty simple Blazor component wrapping the Blazor.Extensions.WebUSB library
public partial class Recordings : ComponentBase
{
[Inject] private IUSB _usb { get; set; }
[Inject] private ILogger<Recordings> _logger { get; set; }
[Inject] private IJSRuntime _runtime { get; set; }
private bool _initialized = false;
protected override Task OnAfterRenderAsync(bool firstRender)
{
if (!_initialized)
{
this._usb.OnConnect += OnConnect;
this._usb.OnDisconnect += OnDisconnect;
this._usb.Initialize();
this._initialized = true;
}
return Task.CompletedTask;
}
protected async Task GetDevices()
{
var devices = await this._usb.GetDevices();
if (devices != null && devices.Length > 0)
{
_logger.LogInformation("Device list received");
}
}
private void OnConnect(USBDevice device)
{
this._logger.LogInformation("Device connected");
}
private void OnDisconnect(USBDevice device)
{
this._logger.LogInformation("Device disconnected");
}
}
And even though I'm doing the JS interop in the OnAfterRenderAsync as suggested I still get the same error. I've tried delaying the call to _usb.Initialize until a button is pressed (meaning the component should definitely have finished rendering.
I've tried disabling prerendering by setting the render-mode attribute in _Host.cshtml to Server instead of ServerPrerendered but nothing changed.