Handling tab switching in Phaser.IO
The gamepad API seems to break in Phaser.IO when the player switches tabs (at least in Chrome). I had a lot of trouble handling this, especially since Chrome wasn't firing window.onblur or window.onfocus, so I couldn't tell when I needed to reboot the gamepad API.
With the help of this Stack Overflow answer, I'm able to detect visibility changes in all browsers (that I've tested) and correctly reboot the gamepad API so that the gamepad continues to work after a tab switch:
(function () {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide
= window.onfocus = window.onblur = onchange;
function onchange(evt) {
var v = "visible", h = "hidden",
evtMap = {
focus: v, focusin: v, pageshow: v, blur: h, focusout: h, pagehide: h
};
evt = evt || window.event;
if (evt.type in evtMap)
document.body.className = evtMap[evt.type];
else
document.body.className = this[hidden] ? "hidden" : "visible";
if (game) {
if (document.body.className.match(/hidden/)) {
game.input.gamepad.stop();
}
else {
game.input.gamepad.start();
}
}
}
// set the initial state (but only if browser supports the Page Visibility API)
if (document[hidden] !== undefined)
onchange({ type: document[hidden] ? "blur" : "focus" });
})();
game = new KGAD.Game(640, 640, 'content');
Next step: figure out why FireFox dpad doesn't work