我试图在服务人员发送消息后播放声音。我一直在遵循本指南,但它总是提供以下错误,交替出现: “未捕获(承诺)错误:无法建立连接。接收端不存在。” “未捕获的错误:扩展上下文无效。”
有人能指出我正确的方向吗?我想我错过了一些明显的东西。预先感谢您!
// Function to check if the conditions are met and click the button
function checkAndClick() {
chrome.runtime.sendMessage({type: "playSoundPlease"});
}
setInterval(checkAndClick, 5000);
<script src="offscreen.js"></script>
// 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();
}
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_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 函数,但无法使其正常工作。
解决了,问题是
<script src="offscreen.js"></script>
而不是scripts/offscreen.js
,错过了。