Windows下Chrome扩展中speechSynthesis.getVoices()返回空数组求助
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.jsonfor Speech Synthesis to work in most cases. - Debugging Tip: If you want to confirm the timing issue, try adding a
setTimeoutaround your originalgetVoices()call (e.g., 2 seconds delay). You’ll likely see the voices load—but using thevoiceschangedevent is the reliable, non-hacky way to handle it.
内容的提问来源于stack exchange,提问作者Melvin Abraham

