phaser/src/core/VisibilityHandler.js

86 lines
2.1 KiB
JavaScript
Raw Normal View History

2018-02-12 16:01:20 +00:00
/**
* @author Richard Davey <rich@photonstorm.com>
2023-01-02 17:36:27 +00:00
* @copyright 2013-2023 Photon Storm Ltd.
2019-05-10 15:15:04 +00:00
* @license {@link https://opensource.org/licenses/MIT|MIT License}
2018-02-12 16:01:20 +00:00
*/
var Events = require('./events');
2018-01-25 02:13:50 +00:00
/**
* The Visibility Handler is responsible for listening out for document level visibility change events.
* This includes `visibilitychange` if the browser supports it, and blur and focus events. It then uses
* the provided Event Emitter and fires the related events.
2017-10-04 22:48:16 +00:00
*
* @function Phaser.Core.VisibilityHandler
* @fires Phaser.Core.Events#BLUR
* @fires Phaser.Core.Events#FOCUS
* @fires Phaser.Core.Events#HIDDEN
* @fires Phaser.Core.Events#VISIBLE
2017-10-04 22:48:16 +00:00
* @since 3.0.0
*
* @param {Phaser.Game} game - The Game instance this Visibility Handler is working on.
2017-10-04 22:48:16 +00:00
*/
var VisibilityHandler = function (game)
{
var hiddenVar;
var eventEmitter = game.events;
if (document.hidden !== undefined)
{
hiddenVar = 'visibilitychange';
}
else
{
var vendors = [ 'webkit', 'moz', 'ms' ];
vendors.forEach(function (prefix)
{
if (document[prefix + 'Hidden'] !== undefined)
{
document.hidden = function ()
{
return document[prefix + 'Hidden'];
};
hiddenVar = prefix + 'visibilitychange';
}
});
}
var onChange = function (event)
{
if (document.hidden || event.type === 'pause')
{
eventEmitter.emit(Events.HIDDEN);
}
else
{
eventEmitter.emit(Events.VISIBLE);
}
};
if (hiddenVar)
{
document.addEventListener(hiddenVar, onChange, false);
}
window.onblur = function ()
{
eventEmitter.emit(Events.BLUR);
};
window.onfocus = function ()
{
eventEmitter.emit(Events.FOCUS);
};
// Automatically give the window focus unless config says otherwise
if (window.focus && game.config.autoFocus)
{
window.focus();
}
};
module.exports = VisibilityHandler;