admin管理员组文章数量:1295773
I am creating a task manager extension. I managed to make notifications work when the task timer ends. The popup appears, and the notification sound plays, but if the extension is minimized, I cannot play the sound. Could I modify it in some way to avoid using offscreen documents?
background.js
let audioContext;
let audioBuffer;
// Initialize the audio when the background is loaded
async function initAudio() {
try {
audioContext = new (AudioContext || webkitAudioContext)();
const response = await fetch(chrome.runtime.getURL('alert.mp3'));
const arrayBuffer = await response.arrayBuffer();
audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
} catch (error) {
console.error('Error initializing the audio:', error);
}
}
// Play the sound
function playSound() {
if (audioContext && audioBuffer) {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(0);
} else {
console.warn('The audio was not initialized correctly.');
}
}
// Listen for messages to play the sound
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'playAlertSound') {
playSound();
}
});
// Handle alarms and notifications
chrome.alarms.onAlarm.addListener((alarm) => {
chrome.notifications.create({
type: 'basic',
iconUrl: 'icon.png',
title: 'Task Reminder!',
message: `It’s time to complete the task: ${alarm.name}`,
priority: 2,
});
playSound(); // Play the sound when an alarm is triggered
});
// Initialize the audio when the background is loaded
initAudio();
**popup.js **
document.addEventListener('DOMContentLoaded', () => {
let tasks = JSON.parse(localStorage.getItem('tasks')) || [];
let editingTask = null;
const addTaskForm = document.getElementById('add-task-form');
const formIcon = document.getElementById('form-icon');
const searchInput = document.getElementById('search-input');
const taskList = document.getElementById('task-list');
let audioContext;
let audioBuffer;
// Initialize the audio context and load the audio file
async function initAudio() {
try {
audioContext = new (window.AudioContext || window.webkitAudioContext)();
const response = await fetch(chrome.runtime.getURL('alert.mp3'));
const arrayBuffer = await response.arrayBuffer();
audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
} catch (error) {
console.error('Error initializing the audio:', error);
}
}
// Play the alert sound
function playSound() {
if (audioBuffer && audioContext) {
const source = audioContext.createBufferSource();
source.buffer = audioBuffer;
source.connect(audioContext.destination);
source.start(0);
} else {
console.warn('Audio not initialized correctly.');
}
}
// Listen for messages from background.js to play the sound
chrome.runtime.onMessage.addListener((message) => {
if (message.type === 'playSound') { // Make sure the type matches with background.js
playSound();
}
});
// Initialize the audio when the popup is loaded
initAudio();
});
In the manifest, I have also declared the permissions, resources, and background.
**manifest.json **
"permissions": [
"storage",
"alarms",
"notifications"
],
"web_accessible_resources": [
{
"resources": ["alert.mp3"],
"matches": ["<all_urls>"]
}
],
"background": {
"service_worker": "background.js"
},
Modify the popup.js to include the play function. Send a message from the background to the popup to trigger the sound.
本文标签: javascriptHow to play a notification sound in a Chrome extension when minimizedStack Overflow
版权声明:本文标题:javascript - How to play a notification sound in a Chrome extension when minimized? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738409688a2085249.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论