The solution I found is fairly straight forward. As you already know you can't use the TTS API in the content scripts. What you have to do is use a background page, or an event page for our purpose since it should be sparsely used.
manifest.json:
...
"permissions": [
"http://*/",
"https://*/",
"tts"
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
tts.js:
document.onkeypress = function() {
if(event.keyCode == 48) { //key '0' pressed
var text = getSelection().toString();
chrome.runtime.sendMessage({type:"tts", text:text});
}
}
background.js:
chrome.runtime.onMessage.addListener(function (request) {
switch(request.type) {
case "tts":
tts(request.text);
break;
}
});
function tts(text) {
chrome.tts.speak(text);
}
or
chrome.runtime.onMessage.addListener(function (request) {
if (request.type == "tts") {
tts(request.text);
}
});
function tts(text) {
chrome.tts.speak(text);
}
Note that type:"tts" is only being used as a key and could be anything else. Also, the tts function doesn't have to match the key. I know this isn't exactly the way you were looking to solve it, but this should handle your problem.
Good luck!