以下HTML在第一次点击时在控制台中显示空数组:
<!DOCTYPE html>
<html>
<head>
<script>
function test(){
console.log(window.speechSynthesis.getVoices())
}
</script>
</head>
<body>
<a href="#" onclick="test()">Test</a>
</body>
</html>
第二次点击您将获得预期的列表。
如果您添加 onload
事件来调用此函数 (<body onload="test()">
),那么您可以在第一次单击时获取正确的结果。请注意,onload
上的第一次调用仍然无法正常工作。它返回空值,但之后可以正常工作。
问题:
由于这可能是 beta 版本中的一个错误,我放弃了“为什么”的问题。
现在,问题是如果您想在页面加载时访问 window.speechSynthesis
:
- 这个问题的最佳解决方法是什么?
- 如何确保它会在页面加载时加载
speechSynthesis
?
背景和测试:
我正在测试 Web Speech API 中的新功能,然后我在我的代码中遇到了这个问题:
<script type="text/javascript">
$(document).ready(function(){
// Browser support messages. (You might need Chrome 33.0 Beta)
if (!('speechSynthesis' in window)) {
alert("You don't have speechSynthesis");
}
var voices = window.speechSynthesis.getVoices();
console.log(voices) // []
$("#test").on('click', function(){
var voices = window.speechSynthesis.getVoices();
console.log(voices); // [SpeechSynthesisVoice, ...]
});
});
</script>
<a id="test" href="#">click here if 'ready()' didn't work</a>
我的问题是:为什么在页面加载完成并触发“onready”函数后,
window.speechSynthesis.getVoices()
返回空数组?如果您点击链接,可以看到相同的函数通过“onclick”触发返回Chrome可用语音的数组?似乎Chrome在页面加载后加载
window.speechSynthesis
!问题不在于“ready”事件。如果我从“ready”函数中删除
var voice=...
这一行,第一次单击时它会在控制台中显示空列表。但第二次单击正常工作。似乎
window.speechSynthesis
需要更多时间才能在第一次调用后加载。您需要调用两次!但是,您还需要等待并让其在对window.speechSynthesis
进行第二次调用之前加载。例如,如果您首次运行以下代码,则会在控制台中显示两个空数组:// First speechSynthesis call
var voices = window.speechSynthesis.getVoices();
console.log(voices);
// Second speechSynthesis call
voices = window.speechSynthesis.getVoices();
console.log(voices);
ready
。 - MehdiTimer
在5秒延迟后调用了getVoices()
,并获得了一个可用语音列表。 - Nawaf AlsulamigetVoices()
两次,间隔一秒,可以解决这个问题。 - Nawaf Alsulami