Как воспроизвести звук уведомления в расширении Chrome при сворачивании?Javascript

Форум по Javascript
Ответить
Anonymous
 Как воспроизвести звук уведомления в расширении Chrome при сворачивании?

Сообщение Anonymous »

Я создаю расширение диспетчера задач. Мне удалось заставить работать уведомления, когда заканчивается таймер задачи. Появляется всплывающее окно и воспроизводится звук уведомления, но если расширение свернуто, я не могу воспроизвести звук. Могу ли я каким-либо образом изменить его, чтобы избежать использования закадровых документов?
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();
});

< /code>
В манифесте я также объявил разрешения, ресурсы и фон. /p>
"permissions": [
"storage",
"alarms",
"notifications"
],
"web_accessible_resources": [
{
"resources": ["alert.mp3"],
"matches": [""]
}
],
"background": {
"service_worker": "background.js"
},
Измените popup.js, включив в него функцию воспроизведения.
Отправьте сообщение из фона во всплывающее окно, чтобы вызвать звук.

Подробнее здесь: https://stackoverflow.com/questions/793 ... -minimized
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»