You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows下Chrome扩展中speechSynthesis.getVoices()返回空数组求助

Fixing speechSynthesis.getVoices() Returning Empty Array in Chrome Extensions

Hey there! I’ve dealt with this exact headache before when working on Chrome extensions that use Speech Synthesis—so let me walk you through why this happens and how to fix it quickly.

Why This Happens

The core issue is that Speech Synthesis voices load asynchronously in Chrome. When you type speechSynthesis.getVoices() directly into the console, you’re probably doing it a few seconds after your extension has loaded, by which time Chrome has finished fetching all available voices. But in your extension’s code, if you call this method too early (like right on script initialization or DOMContentLoaded), the voices haven’t finished loading yet, hence the empty array.

The Solution: Listen for the voiceschanged Event

Chrome fires a voiceschanged event once the speech voices are fully loaded (or if the list of voices changes later). You need to hook into this event to safely access the voice list. Here’s a robust implementation:

// Initialize voice variable
let availableVoices = [];

// First, check if voices are already loaded
availableVoices = speechSynthesis.getVoices();

if (availableVoices.length === 0) {
  // If not, wait for the voiceschanged event
  speechSynthesis.onvoiceschanged = () => {
    availableVoices = speechSynthesis.getVoices();
    console.log("Voices loaded successfully:", availableVoices);
    // Call your voice-dependent logic here
    initializeSpeechFeatures(availableVoices);
  };
} else {
  // Voices are already ready to use
  console.log("Voices available immediately:", availableVoices);
  initializeSpeechFeatures(availableVoices);
}

// Example function to use the voices
function initializeSpeechFeatures(voices) {
  const sampleUtterance = new SpeechSynthesisUtterance("Hello from your Chrome Extension!");
  // Pick a voice (e.g., the first one in the list)
  sampleUtterance.voice = voices[0];
  speechSynthesis.speak(sampleUtterance);
}

Additional Notes for Chrome Extensions

  • Content Scripts vs. Background Scripts: If you’re running this code in a content script, the context should still work fine—just make sure the page you’re injecting into doesn’t have any restrictions on Speech Synthesis.
  • No Extra Permissions Needed: You don’t need to add any special permissions to your manifest.json for Speech Synthesis to work in most cases.
  • Debugging Tip: If you want to confirm the timing issue, try adding a setTimeout around your original getVoices() call (e.g., 2 seconds delay). You’ll likely see the voices load—but using the voiceschanged event is the reliable, non-hacky way to handle it.

内容的提问来源于stack exchange,提问作者Melvin Abraham

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:16:30