开发Chrome无障碍扩展:能否在chrome.tabs.executeScript()中调用chrome.tts.speak()?
chrome.tts.speak() inside chrome.tabs.executeScript()? Short answer: No, you can’t directly call chrome.tts.speak() from a content script injected via chrome.tabs.executeScript(). Here’s why, and how to work around it:
Why the restriction?
Content scripts run in an isolated world separate from your extension's core context (like background scripts or popups). They only have access to a small subset of Chrome’s extension APIs—chrome.tts is not one of them. This API is restricted to extension contexts that have direct access to the browser’s internal services, which content scripts don’t.
The Solution: Communicate between content script and background
You’ll need to send the selected text from your injected content script to your extension’s background service worker (or background page for Manifest V2), then trigger the TTS from there. Here’s how to implement this:
1. Send the selected text from the content script
In the code you inject via executeScript, grab the selected text and send it to the background using chrome.runtime.sendMessage():
// In your injected content script const selectedText = window.getSelection().toString(); if (selectedText.trim()) { chrome.runtime.sendMessage({ type: "SPEAK_TEXT", content: selectedText }); }
2. Listen for the message in the background service worker
In your background script, set up a listener to receive the message and call chrome.tts.speak():
// In background.js (Manifest V3) or background.html (Manifest V2) chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { if (message.type === "SPEAK_TEXT" && message.content) { chrome.tts.speak(message.content, { rate: 1.0, // Adjust speech speed (0.1 to 10) lang: "en-US", // Set desired language enqueue: false // Replace any ongoing speech }); } });
3. Update your manifest for permissions
Make sure your manifest.json includes the necessary permissions to use TTS and send messages:
// Manifest V3 example { "manifest_version": 3, "name": "Your Accessibility Extension", "version": "1.0", "permissions": ["tts", "activeTab", "scripting"], "background": { "service_worker": "background.js" }, // Add other fields like action, icons, etc. }
For Manifest V2, replace "scripting" with "tabs" and use "background": { "page": "background.html" } instead of a service worker.
Quick Note
If you’re using Manifest V3, chrome.tabs.executeScript() is deprecated—you should use chrome.scripting.executeScript() instead, which requires the "scripting" permission in your manifest.
内容的提问来源于stack exchange,提问作者Giles Goat-boy

