0

I am trying to play an audio file from my content.js file but it is not working. I tried sending a message to popup.js and have popup.js play the sound but that only works when the popup is open.

I need a way to play audio from content.js as long as we are on the same page or if we refresh

I am able to click a button in popup.html and get an audio to play because I can play audio in popup.js, but not in content.js.

So please help me

manifest.json

{
"manifest_version": 3, 
"name": "Test", 
"version": "1.0", 
"description": "test app", 
"icons": {
    "128": "Icon-128.png", 
    "48": "Icon-48.png", 
    "16": "Icon-16.png"
}, 
"action": {
    "default_icon" : "Icon-16.png", 
    "default_popup": "popup.html",
    "default_title": "Test"
},
"background": {
    "service_worker": "eventPage.js"
}, 
"content_scripts": [
    {
        "matches": ["https://google.com"],
        "js": ["content.js"]
    }
],
"host_permissions": [
    "https://google.com"
  ],
"permissions": [
    "tabs",
    "scripting"
]

}

content.js

    let interval = null;

function start() {
  interval = setInterval(() => {
    console.log("************************************");
    var sound = new Audio(chrome.runtime.getURL("alert.mp3"));
    sound.play();
  }, 4000);
}

function stop() {
  clearInterval(interval);
  interval = null;
}

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request == "scriptRunning?") {
    if (interval == null) {
      sendResponse(false);
    } else {
      sendResponse(true);
    }
  } else if (request == "toggleScript") {
    if (interval == null) {
      console.log("Starting script");
      start();
      sendResponse(true);
    } else {
      console.log("Stopping script");
      stop();
      sendResponse(false);
    }
  }
  return true;
});

popup.js

    var greet = document.getElementById("greet");
const btn = document.getElementById("btn");

// chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
//   if (request === "playSound") {
//     var sound = new Audio(chrome.runtime.getURL("alert.mp3"));
//     sound.play();
//   }
//   sendResponse("sound played");
// });

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  chrome.tabs.sendMessage(tabs[0].id, "scriptRunning?", function (response) {
    if (response == true) {
      btn.innerHTML = "Stop";
    } else {
      btn.innerHTML = "Start";
    }
  });
});

async function handleBtnClick() {
  await chrome.tabs.query(
    { active: true, currentWindow: true },
    function (tabs) {
      chrome.tabs.sendMessage(tabs[0].id, "toggleScript", function (response) {
        if (response == true) {
          btn.innerHTML = "Stop";
        } else {
          btn.innerHTML = "Start";
        }
      });
    }
  );


}

btn.addEventListener("click", handleBtnClick);

0 Answers0