mistymints
mistymints

Reputation: 43

How do I add a button that plays audio onclick in Chrome Extension?

I am building a simple Chrome Extension pop-up that involves playing audio by clicking on a button. While the html5 tag for <audio controls> works fine, I was looking for a way to discard the default setup provided by html5 and customize the layout instead. Now here is where the problem lies: I now have a button, but it does not play any audio when I click on it.

popup.html

<audio id="my-audio" src="chrome-extension://[MY_ID]/audios/rain.mp3" type="audio/mp3"></audio>
<button id="play">Play</button>

popup.js

let myAudio = document.getElementById('my-audio');
let playButton = document.getElementById('play');

playButton.addEventListener("click", function(){
    myAudio.play()
});

manifest.json

{
  "name": ...,
  "description": ...,
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html",
    "host_permissions": ["<all_urls>"],
  },
}

My background.js is currently empty, and no errors are shown when I run the extension. I used my extension ID to access the audio file, which worked well when I used the <audio> tag.

Any help with identifying the problem would be greatly appreciated.

Upvotes: 0

Views: 906

Answers (1)

Robbi
Robbi

Reputation: 1507

You are probably facing the classic "egg and chicken" problem :-)
When you trying to play the audio file this latter is not ready yet to be played. Wrap the popup.js code inside a DomContentLoaded event handler.

Upvotes: 1

Related Questions