Skip to content

Instantly share code, notes, and snippets.

@paceaux
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paceaux/9402458 to your computer and use it in GitHub Desktop.
Save paceaux/9402458 to your computer and use it in GitHub Desktop.
Page Visibility + speech
var tabAway;
tabAway = {
init: function () {
var _this = tabAway;
_this.bindEvents();
},
data: {
tabAwayMsg: "Don't go, I need you!",
tabBackMsg: "I knew you'd never leave me",
},
helpers: {
hiddenProp: function () {
var prefixes = ['webkit','moz','ms','o'];
if ('hidden' in document) return 'hidden';
for (var i = 0; i < prefixes.length; i++){
if ((prefixes[i] + 'Hidden') in document){
return prefixes[i] + 'Hidden';
}
}
return null;
},
isHidden: function () {
var _this = tabAway,
prop = _this.helpers.hiddenProp();
if (!prop) return false;
return document[prop];
},
createSpeech: function (msg) {
return new SpeechSynthesisUtterance(msg);
}
},
bindEvents: function () {
var _this = tabAway,
visProp = _this.helpers.hiddenProp();
if (visProp) {
var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
document.addEventListener(evtname, _this.functions.handleVischange);
}
},
functions :{
handleVischange: function () {
var _this = tabAway,
hidden = _this.helpers.isHidden(),
msg = hidden === true ? _this.data.tabAwayMsg : _this.data.tabBackMsg,
spokenMsg = _this.helpers.createSpeech(msg);
console.log(msg);
_this.functions.speakMessage(spokenMsg);
},
speakMessage: function (msg) {
window.speechSynthesis.speak(msg);
}
}
}
tabAway.init();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment