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 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 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()
25 // Ensure the global `wp` object exists.
26 window.wp = window.wp || {};
29 var Heartbeat = function() {
33 screenId = typeof pagenow != 'undefined' ? pagenow : '',
34 url = typeof ajaxurl != 'undefined' ? ajaxurl : '',
47 frameBlurTimeout = -1,
48 hasConnectionError = null;
51 * Returns a boolean that's indicative of whether or not there is a connection error
55 this.hasConnectionError = function() {
56 return !! hasConnectionError;
59 if ( typeof( window.heartbeatSettings ) == 'object' ) {
60 settings = $.extend( {}, window.heartbeatSettings );
63 url = settings.ajaxurl || url;
64 delete settings.ajaxurl;
65 delete settings.nonce;
67 interval = settings.interval || 15; // default interval
68 delete settings.interval;
69 // The interval can be from 15 to 60 sec. and can be set temporarily to 5 sec.
72 else if ( interval > 60 )
75 interval = interval * 1000;
77 // 'screenId' can be added from settings on the front-end where the JS global 'pagenow' is not set
78 screenId = screenId || settings.screenId || 'front';
79 delete settings.screenId;
81 // Add or overwrite public vars
82 $.extend( this, settings );
87 return parseInt( (new Date()).getTime() / 1000 );
89 return (new Date()).getTime();
92 function isLocalFrame( frame ) {
93 var origin, src = frame.src;
95 if ( src && /^https?:\/\//.test( src ) ) {
96 origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
98 if ( src.indexOf( origin ) !== 0 )
103 if ( frame.contentWindow.document )
110 // Set error state and fire an event on XHR errors or timeout
111 function errorstate( error, status ) {
120 // no response for 30 sec.
129 if ( errorcount > 2 )
135 if ( 503 == status && false === hasConnectionError ) {
139 if ( trigger && ! self.hasConnectionError() ) {
140 hasConnectionError = true;
141 $(document).trigger( 'heartbeat-connection-lost', [error, status] );
143 } else if ( self.hasConnectionError() ) {
145 hasConnectionError = false;
146 $(document).trigger( 'heartbeat-connection-restored' );
147 } else if ( null === hasConnectionError ) {
148 hasConnectionError = false;
153 var send = {}, data, i, empty = true,
154 nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : '';
157 data = $.extend( {}, queue );
158 // Clear the data queue, anything added after this point will be send on the next tick
161 $(document).trigger( 'heartbeat-send', [data] );
164 if ( data.hasOwnProperty( i ) ) {
170 // If nothing to send (nothing is expecting a response),
171 // schedule the next tick and bail
172 if ( empty && ! self.hasConnectionError() ) {
179 send.interval = interval / 1000;
181 send.action = 'heartbeat';
182 send.screen_id = screenId;
183 send.has_focus = hasFocus;
189 timeout: 30000, // throw an error if not completed after 30 sec.
192 }).done( function( response, textStatus, jqXHR ) {
196 return errorstate( 'empty' );
199 if ( self.hasConnectionError() )
202 if ( response.nonces_expired ) {
203 $(document).trigger( 'heartbeat-nonces-expired' );
207 // Change the interval from PHP
208 if ( response.heartbeat_interval ) {
209 new_interval = response.heartbeat_interval;
210 delete response.heartbeat_interval;
213 self.tick( response, textStatus, jqXHR );
215 // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast'
217 self.interval.call( self, new_interval );
218 }).always( function() {
221 }).fail( function( jqXHR, textStatus, error ) {
222 errorstate( textStatus || 'unknown', jqXHR.status );
223 self.error( jqXHR, textStatus, error );
228 var delta = time() - tick, t = interval;
234 t = 100000; // 100 sec. Post locks expire after 120 sec.
235 } else if ( countdown > 0 && tempInterval ) {
240 window.clearTimeout(beat);
243 beat = window.setTimeout(
256 window.clearTimeout(winBlurTimeout);
257 window.clearTimeout(frameBlurTimeout);
258 winBlurTimeout = frameBlurTimeout = 0;
264 window.clearTimeout(winBlurTimeout);
265 window.clearTimeout(frameBlurTimeout);
266 winBlurTimeout = frameBlurTimeout = 0;
268 isUserActive = time();
274 window.clearTimeout(beat);
280 function setFrameEvents() {
281 $('iframe').each( function( i, frame ){
282 if ( ! isLocalFrame( frame ) )
285 if ( $.data( frame, 'wp-heartbeat-focus' ) )
288 $.data( frame, 'wp-heartbeat-focus', 1 );
290 $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) {
292 }).on('blur.wp-heartbeat-focus', function(e) {
294 frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
299 $(window).on( 'blur.wp-heartbeat-focus', function(e) {
301 winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
302 }).on( 'focus.wp-heartbeat-focus', function() {
303 $('iframe').each( function( i, frame ) {
304 if ( !isLocalFrame( frame ) )
307 $.removeData( frame, 'wp-heartbeat-focus' );
308 $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
314 function userIsActive() {
315 userActiveEvents = false;
316 $(document).off( '.wp-heartbeat-active' );
317 $('iframe').each( function( i, frame ) {
318 if ( ! isLocalFrame( frame ) )
321 $( frame.contentWindow ).off( '.wp-heartbeat-active' );
327 // Set 'hasFocus = true' if user is active and the window is in the background.
328 // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus.
329 function checkUserActive() {
330 var lastActive = isUserActive ? time() - isUserActive : 0;
332 // Throttle down when no mouse or keyboard activity for 5 min
333 if ( lastActive > 300000 && hasFocus )
336 if ( ! userActiveEvents ) {
337 $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
339 $('iframe').each( function( i, frame ) {
340 if ( ! isLocalFrame( frame ) )
343 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
346 userActiveEvents = true;
350 // Check for user activity every 30 seconds.
351 window.setInterval( function(){ checkUserActive(); }, 30000 );
352 $(document).ready( function() {
353 // Start one tick (15 sec) after DOM ready
359 this.hasFocus = function() {
364 * Get/Set the interval
366 * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
367 * If the window doesn't have focus, the interval slows down to 2 min.
369 * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec)
370 * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back
371 * @return int Current interval in seconds
373 this.interval = function( speed, ticks ) {
375 ticks = parseInt( ticks, 10 ) || 30;
376 ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
389 // Allow long polling, (experimental)
398 // Reset when the new interval value is lower than the current one
399 reset = seconds * 1000 < interval;
401 if ( countdown > 0 ) {
402 tempInterval = seconds * 1000;
404 interval = seconds * 1000;
415 return tempInterval ? tempInterval / 1000 : interval / 1000;
419 * Enqueue data to send with the next XHR
421 * As the data is sent later, this function doesn't return the XHR response.
422 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
423 * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
426 * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
427 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
429 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
430 * $param mixed data The data to send.
431 * $param bool dont_overwrite Whether to overwrite existing data in the queue.
432 * $return bool Whether the data was queued or not.
434 this.enqueue = function( handle, data, dont_overwrite ) {
436 if ( dont_overwrite && this.isQueued( handle ) )
439 queue[handle] = data;
446 * Check if data with a particular handle is queued
448 * $param string handle The handle for the data
449 * $return bool Whether some data is queued with this handle
451 this.isQueued = function( handle ) {
453 return queue.hasOwnProperty( handle );
457 * Remove data with a particular handle from the queue
459 * $param string handle The handle for the data
462 this.dequeue = function( handle ) {
464 delete queue[handle];
468 * Get data that was enqueued with a particular handle
470 * $param string handle The handle for the data
471 * $return mixed The data or undefined
473 this.getQueuedItem = function( handle ) {
475 return this.isQueued( handle ) ? queue[handle] : undefined;
479 $.extend( Heartbeat.prototype, {
480 tick: function( data, textStatus, jqXHR ) {
481 $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] );
483 error: function( jqXHR, textStatus, error ) {
484 $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
488 wp.heartbeat = new Heartbeat();