0
I have to create an audible alert for a chat application, I am using the native audio library of javascript, the problem is that many times, this alert is blocked by the browser, this happened when the user loads the page and does not interact with it (This has happened a lot by the way). the following error is displayed on the console
Uncaught (in Promise) Domexception: play() failed because the user didn’t Interact with the Document first
I know there’s a possibility of forcing the guy to click on something as soon as he opens the page, but the project is almost done, and my boss doesn’t see it well.
So, someone would know if there’s a better way out, something like visual alerts, that the browser asks if the guy allows the site to send. or some other solution, I don’t know.
Code responsible for the alert
function play_sound(thesound)
{
let audio = new Audio(base_url + '/media/mp3/' + thesound + '.mp3');
audio.muted = true;
var playPromise = audio.play();
if (playPromise != undefined) {
playPromise.then(_ => {
audio.pause();
})
.catch(error => {
console.error(error);
});
}
}
Show me your code, buddy.
– Weslley Araújo
The mistake says it all. You can’t give
playin a media (as audio) if the user has not interacted with the page before. There is not much to do besides comply with the "limitation" (safety, by the way) of the platform.– Luiz Felipe
@Weslleyaraújo, Sorry, I’ve already added the part of the code that makes the alert friend.
– Carlos Henrique
@Luizfelipe, unfortunately I am coming to this conclusion, I just think that the platform should allow a way for the user to receive alert from a particular site, in the case of my application (chat), it is common for the operator to open the terminal and wait for a call, without interacting with it before, anyway, I think I’m going to have to force a way for the guy to interact with the page when opening it. But this leaves me a doubt, the guy interacted but stayed an hour without doing anything, the browser will back to block the audible alert? or this happens only when you load the page?
– Carlos Henrique
I don’t know, it doesn’t seem clear. Why do you want to emit a sound effect as soon as the page loads and the user hasn’t interacted with it yet? Can you explain the scenario better?
– Raizant
@Raizant, is a chat, imagine the following, the operator clicks on answer chat and a new tab is opened with the answering terminal, usually before receiving the first call, the operator has not yet made any interaction with the page, making the first service of the day not notified.
– Carlos Henrique