But if I want to mute any sound whatsoever from a tab by vanilla JavaScript, is it possible?
If I would have needed to bet, I would have bet that it is not possible because the Window layer of JavaScript is one layer down from the Browser layer, but I might be wrong and it is indeed possible.
An audio element doesn’t have to be attached in order to play, so querying the document will indeed not work reliably. As a minimal example, you could also start playing like so:
new Audio('my-audio-url.mp3').addEventListener('canplay', event => event.target.play())
The if is there is an insurance to prevent abrupt termination of a longer script file that does other things as well (such as removing images and videos), but to the main issue:
I don’t think it matters if the interval is set to 1 ms or 5,000 ms, but anyway such a code doesn’t prevent audio playing there:
I think that the event listening approach here is indeed more reliable
But let’s say that I don’t know what is the name of the audio file that is being played, I just want to stop all audio whatsoever on a webpage, however it is being played.
Is there a JavaScript way to do that automatically?
I tested your code without audio.remove() on an <audio> player (within the HTML DOM) and it worked (with and without the ‘if’). However, I did increase the interval to make sure 1ms is not too short. Incresing the interval to 5000ms enabled me to confirm that the audio paused after about 5 seconds.
Sorry that’s a misunderstanding, I just wanted to demonstrate how you can play audio without having an audio element attached to the document. This means you can not stop it reliably from within another script.
As for listening to media events on the window, this won’t work either I’m afraid since these events (play, playing etc.) do not bubble.
By the way, I have asked ChatGPT the following question:
How to mute all sound in a web browser tab with JavaScript?
The answer (which they ask not to paste in other websites to not mislead their algorithm) mentioned only audio and video elements so ChatGPT failed to provide an answer about how to mute sound that doesn’t arrive fromaudio elements.