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 together with tempInterval
63 // Whether a connection is currently in progress
66 // Whether a connection error occured
67 connectionError: false,
69 // Used to track non-critical errors
72 // Whether at least one connection has completed successfully
75 // Whether the current browser window is in focus and the user is active
78 // Timestamp, last time the user was active. Checked every 30 sec.
81 // Flags whether events tracking user activity were set
82 userActivityEvents: false,
84 // References to various timeouts
91 * Set local vars and events, then start
97 function initialize() {
98 if ( typeof window.pagenow === 'string' ) {
99 settings.screenId = window.pagenow;
102 if ( typeof window.ajaxurl === 'string' ) {
103 settings.url = window.ajaxurl;
106 // Pull in options passed from PHP
107 if ( typeof window.heartbeatSettings === 'object' ) {
108 var options = window.heartbeatSettings;
110 // The XHR URL can be passed as option when window.ajaxurl is not set
111 if ( ! settings.url && options.ajaxurl ) {
112 settings.url = options.ajaxurl;
115 // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
116 if ( options.interval ) {
117 settings.mainInterval = options.interval;
119 if ( settings.mainInterval < 15 ) {
120 settings.mainInterval = 15;
121 } else if ( settings.mainInterval > 60 ) {
122 settings.mainInterval = 60;
126 // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
127 if ( ! settings.screenId ) {
128 settings.screenId = options.screenId || 'front';
131 if ( options.suspension === 'disable' ) {
132 settings.suspendEnabled = false;
136 // Convert to milliseconds
137 settings.mainInterval = settings.mainInterval * 1000;
138 settings.originalInterval = settings.mainInterval;
140 // Set focus/blur events on the window
141 $(window).on( 'blur.wp-heartbeat-focus', function() {
142 setFrameFocusEvents();
143 // We don't know why the 'blur' was fired. Either the user clicked in an iframe or outside the browser.
144 // Running blurred() after some timeout lets us cancel it if the user clicked in an iframe.
145 settings.winBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
146 }).on( 'focus.wp-heartbeat-focus', function() {
147 removeFrameFocusEvents();
149 }).on( 'unload.wp-heartbeat', function() {
150 // Don't connect any more
151 settings.suspend = true;
153 // Abort the last request if not completed
154 if ( settings.xhr && settings.xhr.readyState !== 4 ) {
155 settings.xhr.abort();
159 // Check for user activity every 30 seconds.
160 window.setInterval( function(){ checkUserActivity(); }, 30000 );
162 // Start one tick after DOM ready
163 $document.ready( function() {
164 settings.lastTick = time();
170 * Return the current time according to the browser
177 return (new Date()).getTime();
181 * Check if the iframe is from the same origin
187 function isLocalFrame( frame ) {
188 var origin, src = frame.src;
190 // Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
191 // It throws uncatchable exceptions.
192 if ( src && /^https?:\/\//.test( src ) ) {
193 origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
195 if ( src.indexOf( origin ) !== 0 ) {
201 if ( frame.contentWindow.document ) {
210 * Set error state and fire an event on XHR errors or timeout
214 * @param string error The error type passed from the XHR
215 * @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
218 function setErrorState( error, status ) {
227 // no response for 30 sec.
231 if ( 503 === status && settings.hasConnected ) {
239 settings.errorcount++;
241 if ( settings.errorcount > 2 && settings.hasConnected ) {
248 if ( trigger && ! hasConnectionError() ) {
249 settings.connectionError = true;
250 $document.trigger( 'heartbeat-connection-lost', [error, status] );
256 * Clear the error state and fire an event
262 function clearErrorState() {
263 // Has connected successfully
264 settings.hasConnected = true;
266 if ( hasConnectionError() ) {
267 settings.errorcount = 0;
268 settings.connectionError = false;
269 $document.trigger( 'heartbeat-connection-restored' );
274 * Gather the data and connect to the server
281 var ajaxData, heartbeatData;
283 // If the connection to the server is slower than the interval,
284 // heartbeat connects as soon as the previous connection's response is received.
285 if ( settings.connecting || settings.suspend ) {
289 settings.lastTick = time();
291 heartbeatData = $.extend( {}, settings.queue );
292 // Clear the data queue, anything added after this point will be send on the next tick
295 $document.trigger( 'heartbeat-send', [ heartbeatData ] );
299 interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
300 _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
302 screen_id: settings.screenId,
303 has_focus: settings.hasFocus
306 settings.connecting = true;
307 settings.xhr = $.ajax({
310 timeout: 30000, // throw an error if not completed after 30 sec.
313 }).always( function() {
314 settings.connecting = false;
316 }).done( function( response, textStatus, jqXHR ) {
320 setErrorState( 'empty' );
326 if ( response.nonces_expired ) {
327 $document.trigger( 'heartbeat-nonces-expired' );
331 // Change the interval from PHP
332 if ( response.heartbeat_interval ) {
333 newInterval = response.heartbeat_interval;
334 delete response.heartbeat_interval;
337 $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
339 // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
341 interval( newInterval );
343 }).fail( function( jqXHR, textStatus, error ) {
344 setErrorState( textStatus || 'unknown', jqXHR.status );
345 $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
350 * Schedule the next connection
352 * Fires immediately if the connection time is longer than the interval.
358 function scheduleNextTick() {
359 var delta = time() - settings.lastTick,
360 interval = settings.mainInterval;
362 if ( settings.suspend ) {
366 if ( ! settings.hasFocus ) {
367 interval = 120000; // 120 sec. Post locks expire after 150 sec.
368 } else if ( settings.countdown > 0 && settings.tempInterval ) {
369 interval = settings.tempInterval;
370 settings.countdown--;
372 if ( settings.countdown < 1 ) {
373 settings.tempInterval = 0;
377 window.clearTimeout( settings.beatTimer );
379 if ( delta < interval ) {
380 settings.beatTimer = window.setTimeout(
392 * Set the internal state when the browser window looses focus
400 settings.hasFocus = false;
404 * Set the internal state when the browser window is focused
412 settings.userActivity = time();
414 // Resume if suspended
415 settings.suspend = false;
417 if ( ! settings.hasFocus ) {
418 settings.hasFocus = true;
424 * Add focus/blur events to all local iframes
426 * Used to detect when focus is moved from the main window to an iframe
432 function setFrameFocusEvents() {
433 $('iframe').each( function( i, frame ) {
434 if ( ! isLocalFrame( frame ) ) {
438 if ( $.data( frame, 'wp-heartbeat-focus' ) ) {
442 $.data( frame, 'wp-heartbeat-focus', 1 );
444 $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function() {
446 }).on('blur.wp-heartbeat-focus', function() {
447 setFrameFocusEvents();
448 // We don't know why 'blur' was fired. Either the user clicked in the main window or outside the browser.
449 // Running blurred() after some timeout lets us cancel it if the user clicked in the main window.
450 settings.frameBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
456 * Remove the focus/blur events to all local iframes
462 function removeFrameFocusEvents() {
463 $('iframe').each( function( i, frame ) {
464 if ( ! isLocalFrame( frame ) ) {
468 $.removeData( frame, 'wp-heartbeat-focus' );
469 $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
474 * Clear the reset timers for focus/blur events on the window and iframes
480 function clearFocusTimers() {
481 window.clearTimeout( settings.winBlurTimer );
482 window.clearTimeout( settings.frameBlurTimer );
486 * Runs when the user becomes active after a period of inactivity
492 function userIsActive() {
493 settings.userActivityEvents = false;
494 $document.off( '.wp-heartbeat-active' );
496 $('iframe').each( function( i, frame ) {
497 if ( ! isLocalFrame( frame ) ) {
501 $( frame.contentWindow ).off( '.wp-heartbeat-active' );
508 * Check for user activity
511 * Sets 'hasFocus = true' if user is active and the window is in the background.
512 * Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
513 * for 5 min. even when the window has focus.
519 function checkUserActivity() {
520 var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
522 if ( lastActive > 300000 && settings.hasFocus ) {
523 // Throttle down when no mouse or keyboard activity for 5 min
527 if ( settings.suspendEnabled && lastActive > 1200000 ) {
528 // Suspend after 20 min. of inactivity
529 settings.suspend = true;
532 if ( ! settings.userActivityEvents ) {
533 $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
535 $('iframe').each( function( i, frame ) {
536 if ( ! isLocalFrame( frame ) ) {
540 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
543 settings.userActivityEvents = true;
550 * Whether the window (or any local iframe in it) has focus, or the user is active
554 function hasFocus() {
555 return settings.hasFocus;
559 * Whether there is a connection error
563 function hasConnectionError() {
564 return settings.connectionError;
568 * Connect asap regardless of 'hasFocus'
570 * Will not open two concurrent connections. If a connection is in progress,
571 * will connect again immediately after the current connection completes.
575 function connectNow() {
576 settings.lastTick = 0;
583 * Should be used only when Heartbeat is performing critical tasks like autosave, post-locking, etc.
584 * Using this on many screens may overload the user's hosting account if several
585 * browser windows/tabs are left open for a long time.
589 function disableSuspend() {
590 settings.suspendEnabled = false;
594 * Get/Set the interval
596 * When setting to 'fast' or 5, by default interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
597 * In this case the number of 'ticks' can be passed as second argument.
598 * If the window doesn't have focus, the interval slows down to 2 min.
600 * @param mixed speed Interval: 'fast' or 5, 15, 30, 60
601 * @param string ticks Used with speed = 'fast' or 5, how many ticks before the interval reverts back
602 * @return int Current interval in seconds
604 function interval( speed, ticks ) {
606 oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
624 // Allow long polling, (experimental)
625 settings.mainInterval = 0;
628 newInterval = settings.originalInterval;
631 if ( 5000 === newInterval ) {
632 ticks = parseInt( ticks, 10 ) || 30;
633 ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
635 settings.countdown = ticks;
636 settings.tempInterval = newInterval;
638 settings.countdown = 0;
639 settings.tempInterval = 0;
640 settings.mainInterval = newInterval;
643 // Change the next connection time if new interval has been set.
644 // Will connect immediately if the time since the last connection
645 // is greater than the new interval.
646 if ( newInterval !== oldInterval ) {
651 return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
655 * Enqueue data to send with the next XHR
657 * As the data is send asynchronously, this function doesn't return the XHR response.
658 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
659 * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
662 * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
663 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
665 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
666 * $param mixed data The data to send.
667 * $param bool noOverwrite Whether to overwrite existing data in the queue.
668 * $return bool Whether the data was queued or not.
670 function enqueue( handle, data, noOverwrite ) {
672 if ( noOverwrite && this.isQueued( handle ) ) {
676 settings.queue[handle] = data;
683 * Check if data with a particular handle is queued
685 * $param string handle The handle for the data
686 * $return bool Whether some data is queued with this handle
688 function isQueued( handle ) {
690 return settings.queue.hasOwnProperty( handle );
695 * Remove data with a particular handle from the queue
697 * $param string handle The handle for the data
700 function dequeue( handle ) {
702 delete settings.queue[handle];
707 * Get data that was enqueued with a particular handle
709 * $param string handle The handle for the data
710 * $return mixed The data or undefined
712 function getQueuedItem( handle ) {
714 return this.isQueued( handle ) ? settings.queue[handle] : undefined;
720 // Expose public methods
723 connectNow: connectNow,
724 disableSuspend: disableSuspend,
726 hasConnectionError: hasConnectionError,
730 getQueuedItem: getQueuedItem
734 // Ensure the global `wp` object exists.
735 window.wp = window.wp || {};
736 window.wp.heartbeat = new Heartbeat();
738 }( jQuery, window ));