So I have this simple page:
@page "/"
@inject IJSRuntime _jsRuntime
<button @onclick="MakeSound">Make sound</button>
<button @onclick="ShowPopUp">Show pop-up</button>
@code
{
protected override void OnInitialized()
{
_jsRuntime.InvokeVoidAsync("makeSound");
_jsRuntime.InvokeVoidAsync("showPopUp");
}
void MakeSound()
{
_jsRuntime.InvokeVoidAsync("makeSound");
}
void ShowPopUp()
{
_jsRuntime.InvokeVoidAsync("showPopUp");
}
}
in which I have 2 buttons: one for playing a sound and one for showing an alert. They work fine but when I try to run these actions at initialization, only the alert message shows up and there's no sound. Why?
By the way, this is the JS, though I have a feeling that the problem is not here:
function makeSound() {
var audio = new Audio("sounds/ding.wav");
audio.play();
}
function showPopUp() {
alert("Hello!");
}
Calling JavaScript function in OnInitialized do not work, because DOM is not rendered yet, OnAftrRender is the right event to call JavaScript functions. So you can try like this
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
_jsRuntime.InvokeVoidAsync("makeSound");
_jsRuntime.InvokeVoidAsync("showPopUp");
}
}