Chrome 扩展 V3 离屏音频由于“接收端不存在”而无法工作。

问题描述 投票:0回答:1

我试图在服务人员发送消息后播放声音。我一直在遵循本指南,但它总是提供以下错误,交替出现: “未捕获(承诺)错误:无法建立连接。接收端不存在。” “未捕获的错误:扩展上下文无效。”

有人能指出我正确的方向吗?我想我错过了一些明显的东西。预先感谢您!

内容.js

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

setInterval(checkAndClick, 5000);

离屏.html

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

离屏.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();
}

背景.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"              
    ]
}

我尝试添加音频和各种其他权限、异步 lambda 函数,但无法使其正常工作。

javascript google-chrome-extension chrome-extension-manifest-v3
1个回答
0
投票

解决了,问题是

<script src="offscreen.js"></script>
而不是
scripts/offscreen.js
,错过了。

© www.soinside.com 2019 - 2024. All rights reserved.