4 * Note: this API is "experimental" meaning it will likely change a lot
5 * in the next few releases based on feedback from 3.6.0. If you intend
6 * to use it, please follow the development closely.
8 * Heartbeat is a simple server polling API that sends XHR requests to
9 * the server every 15 - 60 seconds and triggers events (or callbacks) upon
10 * receiving data. Currently these 'ticks' handle transports for post locking,
11 * login-expiration warnings, and related tasks while a user is logged in.
13 * Available PHP filters (in ajax-actions.php):
14 * - heartbeat_received
17 * - heartbeat_nopriv_received
18 * - heartbeat_nopriv_send
19 * - heartbeat_nopriv_tick
20 * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
22 * Custom jQuery events:
26 * - heartbeat-connection-lost
27 * - heartbeat-connection-restored
28 * - heartbeat-nonces-expired
33 ( function( $, window, undefined ) {
34 var Heartbeat = function() {
35 var $document = $(document),
40 // Whether suspending is enabled
43 // Current screen id, defaults to the JS global 'pagenow' when present (in the admin) or 'front'
46 // XHR request URL, defaults to the JS global 'ajaxurl' when present
49 // Timestamp, start of the last connection request
52 // Container for the enqueued items
55 // Connect interval (in seconds)
58 // Used when the interval is set to 5 sec. temporarily
61 // Used when the interval is reset
64 // Used together with tempInterval
67 // Whether a connection is currently in progress
70 // Whether a connection error occured
71 connectionError: false,
73 // Used to track non-critical errors
76 // Whether at least one connection has completed successfully
79 // Whether the current browser window is in focus and the user is active
82 // Timestamp, last time the user was active. Checked every 30 sec.
85 // Flags whether events tracking user activity were set
86 userActivityEvents: false,
88 // References to various timeouts
95 * Set local vars and events, then start
101 function initialize() {
102 if ( typeof window.pagenow === 'string' ) {
103 settings.screenId = window.pagenow;
106 if ( typeof window.ajaxurl === 'string' ) {
107 settings.url = window.ajaxurl;
110 // Pull in options passed from PHP
111 if ( typeof window.heartbeatSettings === 'object' ) {
112 var options = window.heartbeatSettings;
114 // The XHR URL can be passed as option when window.ajaxurl is not set
115 if ( ! settings.url && options.ajaxurl ) {
116 settings.url = options.ajaxurl;
119 // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
120 if ( options.interval ) {
121 settings.mainInterval = options.interval;
123 if ( settings.mainInterval < 15 ) {
124 settings.mainInterval = 15;
125 } else if ( settings.mainInterval > 60 ) {
126 settings.mainInterval = 60;
130 // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
131 if ( ! settings.screenId ) {
132 settings.screenId = options.screenId || 'front';
135 if ( options.suspension === 'disable' ) {
136 settings.suspendEnabled = false;
140 // Convert to milliseconds
141 settings.mainInterval = settings.mainInterval * 1000;
142 settings.originalInterval = settings.mainInterval;
144 // Set focus/blur events on the window
145 $(window).on( 'blur.wp-heartbeat-focus', function() {
146 setFrameFocusEvents();
147 // We don't know why the 'blur' was fired. Either the user clicked in an iframe or outside the browser.
148 // Running blurred() after some timeout lets us cancel it if the user clicked in an iframe.
149 settings.winBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
150 }).on( 'focus.wp-heartbeat-focus', function() {
151 removeFrameFocusEvents();
153 }).on( 'unload.wp-heartbeat', function() {
154 // Don't connect any more
155 settings.suspend = true;
157 // Abort the last request if not completed
158 if ( settings.xhr && settings.xhr.readyState !== 4 ) {
159 settings.xhr.abort();
163 // Check for user activity every 30 seconds.
164 window.setInterval( function(){ checkUserActivity(); }, 30000 );
166 // Start one tick after DOM ready
167 $document.ready( function() {
168 settings.lastTick = time();
174 * Return the current time according to the browser
181 return (new Date()).getTime();
185 * Check if the iframe is from the same origin
191 function isLocalFrame( frame ) {
192 var origin, src = frame.src;
194 // Need to compare strings as WebKit doesn't throw JS errors when iframes have different origin.
195 // It throws uncatchable exceptions.
196 if ( src && /^https?:\/\//.test( src ) ) {
197 origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
199 if ( src.indexOf( origin ) !== 0 ) {
205 if ( frame.contentWindow.document ) {
214 * Set error state and fire an event on XHR errors or timeout
218 * @param string error The error type passed from the XHR
219 * @param int status The HTTP status code passed from jqXHR (200, 404, 500, etc.)
222 function setErrorState( error, status ) {
231 // no response for 30 sec.
235 if ( 503 === status && settings.hasConnected ) {
243 settings.errorcount++;
245 if ( settings.errorcount > 2 && settings.hasConnected ) {
252 if ( trigger && ! hasConnectionError() ) {
253 settings.connectionError = true;
254 $document.trigger( 'heartbeat-connection-lost', [error, status] );
260 * Clear the error state and fire an event
266 function clearErrorState() {
267 // Has connected successfully
268 settings.hasConnected = true;
270 if ( hasConnectionError() ) {
271 settings.errorcount = 0;
272 settings.connectionError = false;
273 $document.trigger( 'heartbeat-connection-restored' );
278 * Gather the data and connect to the server
285 var ajaxData, heartbeatData;
287 // If the connection to the server is slower than the interval,
288 // heartbeat connects as soon as the previous connection's response is received.
289 if ( settings.connecting || settings.suspend ) {
293 settings.lastTick = time();
295 heartbeatData = $.extend( {}, settings.queue );
296 // Clear the data queue, anything added after this point will be send on the next tick
299 $document.trigger( 'heartbeat-send', [ heartbeatData ] );
303 interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
304 _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
306 screen_id: settings.screenId,
307 has_focus: settings.hasFocus
310 settings.connecting = true;
311 settings.xhr = $.ajax({
314 timeout: 30000, // throw an error if not completed after 30 sec.
317 }).always( function() {
318 settings.connecting = false;
320 }).done( function( response, textStatus, jqXHR ) {
324 setErrorState( 'empty' );
330 if ( response.nonces_expired ) {
331 $document.trigger( 'heartbeat-nonces-expired' );
335 // Change the interval from PHP
336 if ( response.heartbeat_interval ) {
337 newInterval = response.heartbeat_interval;
338 delete response.heartbeat_interval;
341 $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
343 // Do this last, can trigger the next XHR if connection time > 5 sec. and newInterval == 'fast'
345 interval( newInterval );
347 }).fail( function( jqXHR, textStatus, error ) {
348 setErrorState( textStatus || 'unknown', jqXHR.status );
349 $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
354 * Schedule the next connection
356 * Fires immediately if the connection time is longer than the interval.
362 function scheduleNextTick() {
363 var delta = time() - settings.lastTick,
364 interval = settings.mainInterval;
366 if ( settings.suspend ) {
370 if ( ! settings.hasFocus ) {
371 interval = 120000; // 120 sec. Post locks expire after 150 sec.
372 } else if ( settings.countdown > 0 && settings.tempInterval ) {
373 interval = settings.tempInterval;
374 settings.countdown--;
376 if ( settings.countdown < 1 ) {
377 settings.tempInterval = 0;
381 window.clearTimeout( settings.beatTimer );
383 if ( delta < interval ) {
384 settings.beatTimer = window.setTimeout(
396 * Set the internal state when the browser window looses focus
404 settings.hasFocus = false;
408 * Set the internal state when the browser window is focused
416 settings.userActivity = time();
418 // Resume if suspended
419 settings.suspend = false;
421 if ( ! settings.hasFocus ) {
422 settings.hasFocus = true;
428 * Add focus/blur events to all local iframes
430 * Used to detect when focus is moved from the main window to an iframe
436 function setFrameFocusEvents() {
437 $('iframe').each( function( i, frame ) {
438 if ( ! isLocalFrame( frame ) ) {
442 if ( $.data( frame, 'wp-heartbeat-focus' ) ) {
446 $.data( frame, 'wp-heartbeat-focus', 1 );
448 $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function() {
450 }).on('blur.wp-heartbeat-focus', function() {
451 setFrameFocusEvents();
452 // We don't know why 'blur' was fired. Either the user clicked in the main window or outside the browser.
453 // Running blurred() after some timeout lets us cancel it if the user clicked in the main window.
454 settings.frameBlurTimer = window.setTimeout( function(){ blurred(); }, 500 );
460 * Remove the focus/blur events to all local iframes
466 function removeFrameFocusEvents() {
467 $('iframe').each( function( i, frame ) {
468 if ( ! isLocalFrame( frame ) ) {
472 $.removeData( frame, 'wp-heartbeat-focus' );
473 $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
478 * Clear the reset timers for focus/blur events on the window and iframes
484 function clearFocusTimers() {
485 window.clearTimeout( settings.winBlurTimer );
486 window.clearTimeout( settings.frameBlurTimer );
490 * Runs when the user becomes active after a period of inactivity
496 function userIsActive() {
497 settings.userActivityEvents = false;
498 $document.off( '.wp-heartbeat-active' );
500 $('iframe').each( function( i, frame ) {
501 if ( ! isLocalFrame( frame ) ) {
505 $( frame.contentWindow ).off( '.wp-heartbeat-active' );
512 * Check for user activity
515 * Sets 'hasFocus = true' if user is active and the window is in the background.
516 * Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity)
517 * for 5 min. even when the window has focus.
523 function checkUserActivity() {
524 var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
526 if ( lastActive > 300000 && settings.hasFocus ) {
527 // Throttle down when no mouse or keyboard activity for 5 min
531 if ( settings.suspendEnabled && lastActive > 1200000 ) {
532 // Suspend after 20 min. of inactivity
533 settings.suspend = true;
536 if ( ! settings.userActivityEvents ) {
537 $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
539 $('iframe').each( function( i, frame ) {
540 if ( ! isLocalFrame( frame ) ) {
544 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
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
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 // Allow long polling, (experimental)
629 settings.mainInterval = 0;
632 newInterval = settings.originalInterval;
635 if ( 5000 === newInterval ) {
636 ticks = parseInt( ticks, 10 ) || 30;
637 ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
639 settings.countdown = ticks;
640 settings.tempInterval = newInterval;
642 settings.countdown = 0;
643 settings.tempInterval = 0;
644 settings.mainInterval = newInterval;
647 // Change the next connection time if new interval has been set.
648 // Will connect immediately if the time since the last connection
649 // is greater than the new interval.
650 if ( newInterval !== oldInterval ) {
655 return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
659 * Enqueue data to send with the next XHR
661 * As the data is send asynchronously, this function doesn't return the XHR response.
662 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
663 * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
666 * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
667 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
669 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
670 * $param mixed data The data to send.
671 * $param bool noOverwrite Whether to overwrite existing data in the queue.
672 * $return bool Whether the data was queued or not.
674 function enqueue( handle, data, noOverwrite ) {
676 if ( noOverwrite && this.isQueued( handle ) ) {
680 settings.queue[handle] = data;
687 * Check if data with a particular handle is queued
689 * $param string handle The handle for the data
690 * $return bool Whether some data is queued with this handle
692 function isQueued( handle ) {
694 return settings.queue.hasOwnProperty( handle );
699 * Remove data with a particular handle from the queue
701 * $param string handle The handle for the data
704 function dequeue( handle ) {
706 delete settings.queue[handle];
711 * Get data that was enqueued with a particular handle
713 * $param string handle The handle for the data
714 * $return mixed The data or undefined
716 function getQueuedItem( handle ) {
718 return this.isQueued( handle ) ? settings.queue[handle] : undefined;
724 // Expose public methods
727 connectNow: connectNow,
728 disableSuspend: disableSuspend,
730 hasConnectionError: hasConnectionError,
734 getQueuedItem: getQueuedItem
738 // Ensure the global `wp` object exists.
739 window.wp = window.wp || {};
740 window.wp.heartbeat = new Heartbeat();
742 }( jQuery, window ));