Olivier Girardot
Olivier Girardot

Reputation: 409

HTML, Javascript game, I would like to find a way to play sound on page display

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?

Upvotes: 1

Views: 171

Answers (1)

codeLearnerrr
codeLearnerrr

Reputation: 300

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.

Upvotes: 1

Related Questions