4 * Heartbeat is a simple server polling API that sends XHR requests to
5 * the server every 15 - 60 seconds and triggers events (or callbacks) upon
6 * receiving data. Currently these 'ticks' handle transports for post locking,
7 * login-expiration warnings, autosave, and related tasks while a user is logged in.
9 * Available PHP filters (in ajax-actions.php):
10 * - heartbeat_received
13 * - heartbeat_nopriv_received
14 * - heartbeat_nopriv_send
15 * - heartbeat_nopriv_tick
16 * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
18 * Custom jQuery events:
22 * - heartbeat-connection-lost
23 * - heartbeat-connection-restored
24 * - heartbeat-nonces-expired
29 ( function( $, window, undefined ) {
30 var Heartbeat = function() {
31 var $document = $(document),
36 // Whether suspending is enabled
39 // Current screen id, defaults to the JS global 'pagenow' when present (in the admin) or 'front'
42 // XHR request URL, defaults to the JS global 'ajaxurl' when present
45 // Timestamp, start of the last connection request
48 // Container for the enqueued items
51 // Connect interval (in seconds)
54 // Used when the interval is set to 5 sec. temporarily
57 // Used when the interval is reset
60 // Used to limit the number of AJAX requests.
63 // Used together with tempInterval
66 // Whether a connection is currently in progress
69 // Whether a connection error occurred
70 connectionError: false,
72 // Used to track non-critical errors
75 // Whether at least one connection has completed successfully
78 // Whether the current browser window is in focus and the user is active
81 // Timestamp, last time the user was active. Checked every 30 sec.
84 // Flags whether events tracking user activity were set
85 userActivityEvents: false,
92 * Set local vars and events, then start
98 function initialize() {
99 var options, hidden, visibilityState, visibilitychange;
101 if ( typeof window.pagenow === 'string' ) {
102 settings.screenId = window.pagenow;
105 if ( typeof window.ajaxurl === 'string' ) {
106 settings.url = window.ajaxurl;
109 // Pull in options passed from PHP
110 if ( typeof window.heartbeatSettings === 'object' ) {
111 options = window.heartbeatSettings;
113 // The XHR URL can be passed as option when window.ajaxurl is not set
114 if ( ! settings.url && options.ajaxurl ) {
115 settings.url = options.ajaxurl;
118 // The interval can be from 15 to 120 sec. and can be set temporarily to 5 sec.
119 // It can be set in the initial options or changed later from JS and/or from PHP.
120 if ( options.interval ) {
121 settings.mainInterval = options.interval;
123 if ( settings.mainInterval < 15 ) {
124 settings.mainInterval = 15;
125 } else if ( settings.mainInterval > 120 ) {
126 settings.mainInterval = 120;
130 // Used to limit the number of AJAX requests. Overrides all other intervals if they are shorter.
131 // Needed for some hosts that cannot handle frequent requests and the user may exceed the allocated server CPU time, etc.
132 // The minimal interval can be up to 600 sec. however setting it to longer than 120 sec. will limit or disable
133 // some of the functionality (like post locks).
134 // Once set at initialization, minimalInterval cannot be changed/overriden.
135 if ( options.minimalInterval ) {
136 options.minimalInterval = parseInt( options.minimalInterval, 10 );
137 settings.minimalInterval = options.minimalInterval > 0 && options.minimalInterval <= 600 ? options.minimalInterval * 1000 : 0;
140 if ( settings.minimalInterval && settings.mainInterval < settings.minimalInterval ) {
141 settings.mainInterval = settings.minimalInterval;
144 // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
145 if ( ! settings.screenId ) {
146 settings.screenId = options.screenId || 'front';
149 if ( options.suspension === 'disable' ) {
150 settings.suspendEnabled = false;
154 // Convert to milliseconds
155 settings.mainInterval = settings.mainInterval * 1000;
156 settings.originalInterval = settings.mainInterval;
158 // Switch the interval to 120 sec. by using the Page Visibility API.
159 // If the browser doesn't support it (Safari < 7, Android < 4.4, IE < 10), the interval
160 // will be increased to 120 sec. after 5 min. of mouse and keyboard inactivity.
161 if ( typeof document.hidden !== 'undefined' ) {
163 visibilitychange = 'visibilitychange';
164 visibilityState = 'visibilityState';
165 } else if ( typeof document.msHidden !== 'undefined' ) { // IE10
167 visibilitychange = 'msvisibilitychange';
168 visibilityState = 'msVisibilityState';
169 } else if ( typeof document.webkitHidden !== 'undefined' ) { // Android
170 hidden = 'webkitHidden';
171 visibilitychange = 'webkitvisibilitychange';
172 visibilityState = 'webkitVisibilityState';
176 if ( document[hidden] ) {
177 settings.hasFocus = false;
180 $document.on( visibilitychange + '.wp-heartbeat', function() {
181 if ( document[visibilityState] === 'hidden' ) {
183 window.clearInterval( settings.checkFocusTimer );
186 if ( document.hasFocus ) {
187 settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
193 // Use document.hasFocus() if available.
194 if ( document.hasFocus ) {
195 settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
198 $(window).on( 'unload.wp-heartbeat', function() {
199 // Don't connect any more
200 settings.suspend = true;
202 // Abort the last request if not completed
203 if ( settings.xhr && settings.xhr.readyState !== 4 ) {
204 settings.xhr.abort();
208 // Check for user activity every 30 seconds.
209 window.setInterval( checkUserActivity, 30000 );
211 // Start one tick after DOM ready
212 $document.ready( function() {
213 settings.lastTick = time();
219 * Return the current time according to the browser
226 return (new Date()).getTime();
230 * Check if the iframe is from the same origin
236 function isLocalFrame( frame ) {
237 var origin, src = frame.src;
239 // Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
240 // It throws uncatchable exceptions.
241 if ( src && /^https?:\/\//.test( src ) ) {
242 origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
244 if ( src.indexOf( origin ) !== 0 ) {
250 if ( frame.contentWindow.document ) {
259 * Check if the document's focus has changed
265 function checkFocus() {
266 if ( settings.hasFocus && ! document.hasFocus() ) {
268 } else if ( ! settings.hasFocus && document.hasFocus() ) {
274 * Set error state and fire an event on XHR errors or timeout
278 * @param string error The error type passed from the XHR
279 * @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
282 function setErrorState( error, status ) {
291 // no response for 30 sec.
295 if ( 503 === status && settings.hasConnected ) {
303 settings.errorcount++;
305 if ( settings.errorcount > 2 && settings.hasConnected ) {
312 if ( trigger && ! hasConnectionError() ) {
313 settings.connectionError = true;
314 $document.trigger( 'heartbeat-connection-lost', [error, status] );
320 * Clear the error state and fire an event
326 function clearErrorState() {
327 // Has connected successfully
328 settings.hasConnected = true;
330 if ( hasConnectionError() ) {
331 settings.errorcount = 0;
332 settings.connectionError = false;
333 $document.trigger( 'heartbeat-connection-restored' );
338 * Gather the data and connect to the server
345 var ajaxData, heartbeatData;
347 // If the connection to the server is slower than the interval,
348 // heartbeat connects as soon as the previous connection's response is received.
349 if ( settings.connecting || settings.suspend ) {
353 settings.lastTick = time();
355 heartbeatData = $.extend( {}, settings.queue );
356 // Clear the data queue, anything added after this point will be send on the next tick
359 $document.trigger( 'heartbeat-send', [ heartbeatData ] );
363 interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
364 _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
366 screen_id: settings.screenId,
367 has_focus: settings.hasFocus
370 settings.connecting = true;
371 settings.xhr = $.ajax({
374 timeout: 30000, // throw an error if not completed after 30 sec.
377 }).always( function() {
378 settings.connecting = false;
380 }).done( function( response, textStatus, jqXHR ) {
384 setErrorState( 'empty' );
390 if ( response.nonces_expired ) {
391 $document.trigger( 'heartbeat-nonces-expired' );
394 // Change the interval from PHP
395 if ( response.heartbeat_interval ) {
396 newInterval = response.heartbeat_interval;
397 delete response.heartbeat_interval;
400 $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
402 // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
404 interval( newInterval );
406 }).fail( function( jqXHR, textStatus, error ) {
407 setErrorState( textStatus || 'unknown', jqXHR.status );
408 $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
413 * Schedule the next connection
415 * Fires immediately if the connection time is longer than the interval.
421 function scheduleNextTick() {
422 var delta = time() - settings.lastTick,
423 interval = settings.mainInterval;
425 if ( settings.suspend ) {
429 if ( ! settings.hasFocus ) {
430 interval = 120000; // 120 sec. Post locks expire after 150 sec.
431 } else if ( settings.countdown > 0 && settings.tempInterval ) {
432 interval = settings.tempInterval;
433 settings.countdown--;
435 if ( settings.countdown < 1 ) {
436 settings.tempInterval = 0;
440 if ( settings.minimalInterval && interval < settings.minimalInterval ) {
441 interval = settings.minimalInterval;
444 window.clearTimeout( settings.beatTimer );
446 if ( delta < interval ) {
447 settings.beatTimer = window.setTimeout(
459 * Set the internal state when the browser window becomes hidden or loses focus
466 settings.hasFocus = false;
470 * Set the internal state when the browser window becomes visible or is in focus
477 settings.userActivity = time();
479 // Resume if suspended
480 settings.suspend = false;
482 if ( ! settings.hasFocus ) {
483 settings.hasFocus = true;
489 * Runs when the user becomes active after a period of inactivity
495 function userIsActive() {
496 settings.userActivityEvents = false;
497 $document.off( '.wp-heartbeat-active' );
499 $('iframe').each( function( i, frame ) {
500 if ( isLocalFrame( frame ) ) {
501 $( frame.contentWindow ).off( '.wp-heartbeat-active' );
509 * Check for user activity
512 * Sets 'hasFocus = true' if user is active and the window is in the background.
513 * Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
514 * for 5 min. even when the window has focus.
520 function checkUserActivity() {
521 var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
523 // Throttle down when no mouse or keyboard activity for 5 min.
524 if ( lastActive > 300000 && settings.hasFocus ) {
528 // Suspend after 10 min. of inactivity when suspending is enabled.
529 // Always suspend after 60 min. of inactivity. This will release the post lock, etc.
530 if ( ( settings.suspendEnabled && lastActive > 600000 ) || lastActive > 3600000 ) {
531 settings.suspend = true;
534 if ( ! settings.userActivityEvents ) {
535 $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
539 $('iframe').each( function( i, frame ) {
540 if ( isLocalFrame( frame ) ) {
541 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
547 settings.userActivityEvents = true;
554 * Whether the window (or any local iframe in it) has focus, or the user is active
558 function hasFocus() {
559 return settings.hasFocus;
563 * Whether there is a connection error
567 function hasConnectionError() {
568 return settings.connectionError;
572 * Connect asap regardless of 'hasFocus'
574 * Will not open two concurrent connections. If a connection is in progress,
575 * will connect again immediately after the current connection completes.
579 function connectNow() {
580 settings.lastTick = 0;
587 * Should be used only when Heartbeat is performing critical tasks like autosave, post-locking, etc.
588 * Using this on many screens may overload the user's hosting account if several
589 * browser windows/tabs are left open for a long time.
593 function disableSuspend() {
594 settings.suspendEnabled = false;
598 * Get/Set the interval
600 * When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
601 * In this case the number of 'ticks' can be passed as second argument.
602 * If the window doesn't have focus, the interval slows down to 2 min.
604 * @param mixed speed Interval: 'fast' or 5, 15, 30, 60, 120
605 * @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
606 * @return int Current interval in seconds
608 function interval( speed, ticks ) {
610 oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
628 newInterval = 120000;
631 // Allow long polling, (experimental)
632 settings.mainInterval = 0;
635 newInterval = settings.originalInterval;
638 if ( settings.minimalInterval && newInterval < settings.minimalInterval ) {
639 newInterval = settings.minimalInterval;
642 if ( 5000 === newInterval ) {
643 ticks = parseInt( ticks, 10 ) || 30;
644 ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
646 settings.countdown = ticks;
647 settings.tempInterval = newInterval;
649 settings.countdown = 0;
650 settings.tempInterval = 0;
651 settings.mainInterval = newInterval;
654 // Change the next connection time if new interval has been set.
655 // Will connect immediately if the time since the last connection
656 // is greater than the new interval.
657 if ( newInterval !== oldInterval ) {
662 return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
666 * Enqueue data to send with the next XHR
668 * As the data is send asynchronously, this function doesn't return the XHR response.
669 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
670 * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
673 * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
674 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
676 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
677 * $param mixed data The data to send.
678 * $param bool noOverwrite Whether to overwrite existing data in the queue.
679 * $return bool Whether the data was queued or not.
681 function enqueue( handle, data, noOverwrite ) {
683 if ( noOverwrite && this.isQueued( handle ) ) {
687 settings.queue[handle] = data;
694 * Check if data with a particular handle is queued
696 * $param string handle The handle for the data
697 * $return bool Whether some data is queued with this handle
699 function isQueued( handle ) {
701 return settings.queue.hasOwnProperty( handle );
706 * Remove data with a particular handle from the queue
708 * $param string handle The handle for the data
711 function dequeue( handle ) {
713 delete settings.queue[handle];
718 * Get data that was enqueued with a particular handle
720 * $param string handle The handle for the data
721 * $return mixed The data or undefined
723 function getQueuedItem( handle ) {
725 return this.isQueued( handle ) ? settings.queue[handle] : undefined;
731 // Expose public methods
734 connectNow: connectNow,
735 disableSuspend: disableSuspend,
737 hasConnectionError: hasConnectionError,
741 getQueuedItem: getQueuedItem
745 // Ensure the global `wp` object exists.
746 window.wp = window.wp || {};
747 window.wp.heartbeat = new Heartbeat();
749 }( jQuery, window ));