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