1

In other words I would like to go around the Chrome settings that prevents sounds from playing on page load (not just on my computer but for every future user). Here is the interesting part of my index: <body onload="playCreditMusic()">

And the javascript function:

const playCreditMusic = () => {
  const audio = new Audio('../sound/sound.mp3');
  audio.play();
};

Here is the error message: DOMException: play() failed because the user didn't interact with the document first.

Does anyone have an idea?

Olivier Girardot
  • 389
  • 4
  • 16

1 Answers1

1

Olivier. Actually there's another way of accomplishing this task. Here's how i did it:

HTML

<figure>
        <figcaption>Listen to the T-Rex:</figcaption>
        <audio
            controls autoplay loop
            src="/media/cc0-audio/t-rex-roar.mp3">
                Your browser does not support the
                <code>audio</code> element.
        </audio>
    </figure>

CSS

figure {
    margin: 0;
    visibility:hidden;
}

Note that i didn't use the onload event or any inline javascript. This is because according to the Content Security Policy (CSP) this makes websites vulnerable to attacks such as code injection and many others. I hope it helped.

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
codeLearnerrr
  • 300
  • 2
  • 10
  • 1
    Thanks a lot! Unfortunately the ```autoplay``` doesn't seem to work. But It's a good start, thanks! – Olivier Girardot Sep 15 '20 at 19:15
  • 1
    Humm.. This is odd. Here's where you can find more about the `audio` tag in the [documentation](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio#:~:text=The%20HTML%20element%20is,streamed%20media%2C%20using%20a%20MediaStream%20.) – codeLearnerrr Sep 15 '20 at 19:23
  • 1
    Thanks I will look into it, but I think chrome blocks the autoplay option. There might be a solution in here though: https://stackoverflow.com/questions/50490304/how-to-make-audio-autoplay-on-chrome#:~:text=The%20default%20HTML5%20audio%20autoplay,getElementById('myAudio'). – Olivier Girardot Sep 16 '20 at 06:39