.NET Core 3.1 でビルドされた Blazor アプリがあり、USB ポート リソースにアクセスできる必要があります。エラーが発生し続けます:
現時点では、JavaScript 相互運用呼び出しを発行できません。これは、コンポーネントが静的にレンダリングされているためです。事前レンダリングが有効になっている場合、JavaScript 相互運用呼び出しは、OnAfterRenderAsync ライフサイクル メソッド中にのみ実行できます。
Blazor.Extensions.WebUSB ライブラリをラップする非常に単純な Blazor コンポーネントがあります。
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");
}
}
そして、提案されているように OnAfterRenderAsync で JS 相互運用を行っていますが、それでも同じエラーが発生します。ボタンが押されるまで _usb.Initialize の呼び出しを遅らせようとしました (つまり、コンポーネントのレンダリングが確実に終了するはずです。
_Host.cshtml の render-mode 属性を ServerPrerendered ではなく Server に設定して、事前レンダリングを無効にしようとしましたが、何も変わりませんでした。