* Heartbeat is a simple server polling API that sends XHR requests to
* the server every 15 - 60 seconds and triggers events (or callbacks) upon
* receiving data. Currently these 'ticks' handle transports for post locking,
* login-expiration warnings, autosave, and related tasks while a user is logged in.
* Available PHP filters (in ajax-actions.php):
* - heartbeat_nopriv_received
* - heartbeat_nopriv_send
* - heartbeat_nopriv_tick
* @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
* - heartbeat-connection-lost
* - heartbeat-connection-restored
* - heartbeat-nonces-expired
* @output wp-includes/js/heartbeat.js
( function( $, window, undefined ) {
* Constructs the Heartbeat API.
* @return {Object} An instance of the Heartbeat class.
var Heartbeat = function() {
var $document = $(document),
// Whether suspending is enabled.
// Current screen id, defaults to the JS global 'pagenow' when present
// (in the admin) or 'front'.
// XHR request URL, defaults to the JS global 'ajaxurl' when present.
// Timestamp, start of the last connection request.
// Container for the enqueued items.
// Connect interval (in seconds).
// Used when the interval is set to 5 seconds temporarily.
// Used when the interval is reset.
// Used to limit the number of Ajax requests.
// Used together with tempInterval.
// Whether a connection is currently in progress.
// Whether a connection error occurred.
// Used to track non-critical errors.
// Whether at least one connection has been completed successfully.
// Whether the current browser window is in focus and the user is active.
// Timestamp, last time the user was active. Checked every 30 seconds.
// Flag whether events tracking user activity were set.
userActivityEvents: false,
// Timer that keeps track of how long a user has focus.
// Timer that keeps track of how long needs to be waited before connecting to
* Sets local variables and events, then starts the heartbeat.
var options, hidden, visibilityState, visibilitychange;
if ( typeof window.pagenow === 'string' ) {
settings.screenId = window.pagenow;
if ( typeof window.ajaxurl === 'string' ) {
settings.url = window.ajaxurl;
// Pull in options passed from PHP.
if ( typeof window.heartbeatSettings === 'object' ) {
options = window.heartbeatSettings;
// The XHR URL can be passed as option when window.ajaxurl is not set.
if ( ! settings.url && options.ajaxurl ) {
settings.url = options.ajaxurl;
* The interval can be from 15 to 120 seconds and can be set temporarily to 5 seconds.
* It can be set in the initial options or changed later through JS and/or through PHP.
if ( options.interval ) {
settings.mainInterval = options.interval;
if ( settings.mainInterval < 15 ) {
settings.mainInterval = 15;
} else if ( settings.mainInterval > 120 ) {
settings.mainInterval = 120;
* Used to limit the number of Ajax requests. Overrides all other intervals
* if they are shorter. Needed for some hosts that cannot handle frequent requests
* and the user may exceed the allocated server CPU time, etc. The minimal interval
* can be up to 600 seconds, however setting it to longer than 120 seconds
* will limit or disable some of the functionality (like post locks).
* Once set at initialization, minimalInterval cannot be changed/overridden.
if ( options.minimalInterval ) {
options.minimalInterval = parseInt( options.minimalInterval, 10 );
settings.minimalInterval = options.minimalInterval > 0 && options.minimalInterval <= 600 ? options.minimalInterval * 1000 : 0;
if ( settings.minimalInterval && settings.mainInterval < settings.minimalInterval ) {
settings.mainInterval = settings.minimalInterval;
// 'screenId' can be added from settings on the front end where the JS global
if ( ! settings.screenId ) {
settings.screenId = options.screenId || 'front';
if ( options.suspension === 'disable' ) {
settings.suspendEnabled = false;
// Convert to milliseconds.
settings.mainInterval = settings.mainInterval * 1000;
settings.originalInterval = settings.mainInterval;
* Switch the interval to 120 seconds by using the Page Visibility API.
* If the browser doesn't support it (Safari < 7, Android < 4.4, IE < 10), the
* interval will be increased to 120 seconds after 5 minutes of mouse and keyboard
if ( typeof document.hidden !== 'undefined' ) {
visibilitychange = 'visibilitychange';
visibilityState = 'visibilityState';
} else if ( typeof document.msHidden !== 'undefined' ) { // IE10.
visibilitychange = 'msvisibilitychange';
visibilityState = 'msVisibilityState';
} else if ( typeof document.webkitHidden !== 'undefined' ) { // Android.
visibilitychange = 'webkitvisibilitychange';
visibilityState = 'webkitVisibilityState';
if ( document[hidden] ) {
settings.hasFocus = false;
$document.on( visibilitychange + '.wp-heartbeat', function() {
if ( document[visibilityState] === 'hidden' ) {
window.clearInterval( settings.checkFocusTimer );
if ( document.hasFocus ) {
settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
// Use document.hasFocus() if available.
if ( document.hasFocus ) {
settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
$(window).on( 'unload.wp-heartbeat', function() {
// Don't connect anymore.
// Abort the last request if not completed.
if ( settings.xhr && settings.xhr.readyState !== 4 ) {
// Check for user activity every 30 seconds.
window.setInterval( checkUserActivity, 30000 );
// Start one tick after DOM ready.
$document.ready( function() {
settings.lastTick = time();
* Returns the current time according to the browser.
* @return {number} Returns the current time.
return (new Date()).getTime();
* Checks if the iframe is from the same origin.
* @return {boolean} Returns whether or not the iframe is from the same origin.
function isLocalFrame( frame ) {
var origin, src = frame.src;
* Need to compare strings as WebKit doesn't throw JS errors when iframes have
* different origin. It throws uncatchable exceptions.
if ( src && /^https?:\/\//.test( src ) ) {
origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
if ( src.indexOf( origin ) !== 0 ) {
if ( frame.contentWindow.document ) {
* Checks if the document's focus has changed.
if ( settings.hasFocus && ! document.hasFocus() ) {
} else if ( ! settings.hasFocus && document.hasFocus() ) {
* Sets error state and fires an event on XHR errors or timeout.
* @param {string} error The error type passed from the XHR.
* @param {number} status The HTTP status code passed from jqXHR
function setErrorState( error, status ) {
// No response for 30 seconds.
if ( 503 === status && settings.hasConnected ) {
if ( settings.errorcount > 2 && settings.hasConnected ) {
if ( trigger && ! hasConnectionError() ) {
settings.connectionError = true;
$document.trigger( 'heartbeat-connection-lost', [error, status] );
wp.hooks.doAction( 'heartbeat.connection-lost', error, status );
* Clears the error state and fires an event if there is a connection error.
function clearErrorState() {
// Has connected successfully.
settings.hasConnected = true;
if ( hasConnectionError() ) {
settings.connectionError = false;
$document.trigger( 'heartbeat-connection-restored' );
wp.hooks.doAction( 'heartbeat.connection-restored' );
* Gathers the data and connects to the server.
var ajaxData, heartbeatData;
// If the connection to the server is slower than the interval,
// heartbeat connects as soon as the previous connection's response is received.
if ( settings.connecting || settings.suspend ) {
settings.lastTick = time();
heartbeatData = $.extend( {}, settings.queue );
// Clear the data queue. Anything added after this point will be sent on the next tick.
$document.trigger( 'heartbeat-send', [ heartbeatData ] );
wp.hooks.doAction( 'heartbeat.send', heartbeatData );
interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
_nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
screen_id: settings.screenId,
has_focus: settings.hasFocus
if ( 'customize' === settings.screenId ) {
ajaxData.wp_customize = 'on';
settings.connecting = true;
timeout: 30000, // Throw an error if not completed after 30 seconds.
settings.connecting = false;
}).done( function( response, textStatus, jqXHR ) {
setErrorState( 'empty' );
if ( response.nonces_expired ) {
$document.trigger( 'heartbeat-nonces-expired' );
wp.hooks.doAction( 'heartbeat.nonces-expired' );
// Change the interval from PHP.
if ( response.heartbeat_interval ) {
newInterval = response.heartbeat_interval;
delete response.heartbeat_interval;
// Update the heartbeat nonce if set.
if ( response.heartbeat_nonce && typeof window.heartbeatSettings === 'object' ) {
window.heartbeatSettings.nonce = response.heartbeat_nonce;
delete response.heartbeat_nonce;
// Update the Rest API nonce if set and wp-api loaded.
if ( response.rest_nonce && typeof window.wpApiSettings === 'object' ) {
window.wpApiSettings.nonce = response.rest_nonce;
// This nonce is required for api-fetch through heartbeat.tick.
// delete response.rest_nonce;
$document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
wp.hooks.doAction( 'heartbeat.tick', response, textStatus, jqXHR );
// Do this last. Can trigger the next XHR if connection time > 5 seconds and newInterval == 'fast'.
}).fail( function( jqXHR, textStatus, error ) {
setErrorState( textStatus || 'unknown', jqXHR.status );
$document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
wp.hooks.doAction( 'heartbeat.error', jqXHR, textStatus, error );
* Schedules the next connection.
* Fires immediately if the connection time is longer than the interval.
function scheduleNextTick() {
var delta = time() - settings.lastTick,
interval = settings.mainInterval;
if ( settings.suspend ) {
if ( ! settings.hasFocus ) {
interval = 120000; // 120 seconds. Post locks expire after 150 seconds.
} else if ( settings.countdown > 0 && settings.tempInterval ) {
interval = settings.tempInterval;
if ( settings.countdown < 1 ) {
settings.tempInterval = 0;
if ( settings.minimalInterval && interval < settings.minimalInterval ) {
interval = settings.minimalInterval;