Chrome Extension V3 offscreen audio not working due to "Receiving end does not exist."

61 Views Asked by At

I am trying to make sound play once a message is sent from the service-worker. I have been following this guide but it always provides the below errors, alternating: "Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist." "Uncaught Error: Extension context invalidated."

Could someone point me in the right direction? I assume I am missing something obvious. Thank you in advance!

content.js

// Function to check if the conditions are met and click the button
function checkAndClick() {
chrome.runtime.sendMessage({type: "playSoundPlease"});
}

setInterval(checkAndClick, 5000);

offscreen.html

<script src="offscreen.js"></script>

offscreen.js

// Listen for messages from the extension
chrome.runtime.onMessage.addListener(msg => {
    if (message.type === "playSoundPlease2") playAudio(msg.play);
});

// Play sound with access to DOM APIs
function playAudio({ source, volume }) {
    const audio = new Audio(source);
    audio.volume = volume;
    audio.play();
}

background.js

chrome.runtime.onMessage.addListener(function(message, sender) {
    if (message.type === "playSoundPlease") {
      playSound();
    }
  });

async function playSound(source = 'notification.mp3', volume = 1) {
    await createOffscreen();
    await chrome.runtime.sendMessage({ play: { source, volume }, type: "playSoundPlease2" });
}

// Create the offscreen document if it doesn't already exist
async function createOffscreen() {
    if (await chrome.offscreen.hasDocument()) return;
    await chrome.offscreen.createDocument({
        url: 'offscreen.html',
        reasons: ['AUDIO_PLAYBACK'],
        justification: 'testing' // details for using the API
    });
}

manifest.json

{
  "manifest_version": 3,
  "name": "Sound Test Manifest V3",
  "version": "1.0",
  "description": "None",
  "host_permissions": [
    "http://*/*",
    "https://*/*"
  ],
  "action": {
    "default_popup": "popup.html"
  },
  "background": {
    "service_worker": "scripts/background.js"
  },
  "content_scripts": [
    {
      "matches": ["https://*"],
      "js": ["scripts/content.js"],
      "run_at": "document_idle"
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["notification.mp3"],
      "matches": ["<all_urls>"]
    }
  ],  
  "permissions": [               
      "offscreen"              
    ]
}

I tried adding Audio and various other permissions, async lambda functions but am not able to get this to work.

1

There are 1 best solutions below

0
clearless On

Resolved it, issue was

<script src="offscreen.js"></script>

instead of scripts/offscreen.js, missed that.