Recipe 9.6

Automatically Pausing Speech

You can listen for the visibilitychange event to automatically pause speech when you switch to another tab, and resume it when you switch back to the tab with speech.

Demo

Code

JavaScript
const content = `
  By listening to the visibilitychange event, you can pause and resume speech when switching tabs. This solution also stops the voice when you leave or refresh the page. Try switching tabs while I'm speaking to see this example in action.
`;

// Clean up speech synthesis on a reload
speechSynthesis.cancel();

document.querySelector('#speak').addEventListener('click', () => {

  const utterance = new SpeechSynthesisUtterance(content);
  speechSynthesis.speak(utterance);
});

document.addEventListener('visibilitychange', event => {
  if (speechSynthesis.speaking) {
    if (document.visibilityState === 'hidden') {
      speechSynthesis.pause();
    } else if (document.visibilityState === 'visible') {
      speechSynthesis.resume();
    }
  }
});
HTML
<button id="speak" class="btn btn-primary">Start Speaking</button>
Web API Cookbook
Joe Attardi