Last active
August 29, 2015 13:57
-
-
Save paceaux/9402458 to your computer and use it in GitHub Desktop.
Page Visibility + speech
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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