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 = false;
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 ) {
120 // no response for 30 sec.
129 if ( errorcount > 2 )
135 if ( trigger && ! self.hasConnectionError() ) {
136 hasConnectionError = true;
137 $(document).trigger( 'heartbeat-connection-lost', [error] );
139 } else if ( self.hasConnectionError() ) {
141 hasConnectionError = false;
142 $(document).trigger( 'heartbeat-connection-restored' );
147 var send = {}, data, i, empty = true,
148 nonce = typeof window.heartbeatSettings == 'object' ? window.heartbeatSettings.nonce : '';
151 data = $.extend( {}, queue );
152 // Clear the data queue, anything added after this point will be send on the next tick
155 $(document).trigger( 'heartbeat-send', [data] );
158 if ( data.hasOwnProperty( i ) ) {
164 // If nothing to send (nothing is expecting a response),
165 // schedule the next tick and bail
166 if ( empty && ! self.hasConnectionError() ) {
173 send.interval = interval / 1000;
175 send.action = 'heartbeat';
176 send.screen_id = screenId;
177 send.has_focus = hasFocus;
183 timeout: 30000, // throw an error if not completed after 30 sec.
186 }).done( function( response, textStatus, jqXHR ) {
190 return errorstate( 'empty' );
193 if ( self.hasConnectionError() )
196 if ( response.nonces_expired ) {
197 $(document).trigger( 'heartbeat-nonces-expired' );
201 // Change the interval from PHP
202 if ( response.heartbeat_interval ) {
203 new_interval = response.heartbeat_interval;
204 delete response.heartbeat_interval;
207 self.tick( response, textStatus, jqXHR );
209 // do this last, can trigger the next XHR if connection time > 5 sec. and new_interval == 'fast'
211 self.interval.call( self, new_interval );
212 }).always( function() {
215 }).fail( function( jqXHR, textStatus, error ) {
216 errorstate( textStatus || 'unknown' );
217 self.error( jqXHR, textStatus, error );
222 var delta = time() - tick, t = interval;
228 t = 100000; // 100 sec. Post locks expire after 120 sec.
229 } else if ( countdown > 0 && tempInterval ) {
234 window.clearTimeout(beat);
237 beat = window.setTimeout(
250 window.clearTimeout(winBlurTimeout);
251 window.clearTimeout(frameBlurTimeout);
252 winBlurTimeout = frameBlurTimeout = 0;
258 window.clearTimeout(winBlurTimeout);
259 window.clearTimeout(frameBlurTimeout);
260 winBlurTimeout = frameBlurTimeout = 0;
262 isUserActive = time();
268 window.clearTimeout(beat);
274 function setFrameEvents() {
275 $('iframe').each( function( i, frame ){
276 if ( ! isLocalFrame( frame ) )
279 if ( $.data( frame, 'wp-heartbeat-focus' ) )
282 $.data( frame, 'wp-heartbeat-focus', 1 );
284 $( frame.contentWindow ).on( 'focus.wp-heartbeat-focus', function(e) {
286 }).on('blur.wp-heartbeat-focus', function(e) {
288 frameBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
293 $(window).on( 'blur.wp-heartbeat-focus', function(e) {
295 winBlurTimeout = window.setTimeout( function(){ blurred(); }, 500 );
296 }).on( 'focus.wp-heartbeat-focus', function() {
297 $('iframe').each( function( i, frame ) {
298 if ( !isLocalFrame( frame ) )
301 $.removeData( frame, 'wp-heartbeat-focus' );
302 $( frame.contentWindow ).off( '.wp-heartbeat-focus' );
308 function userIsActive() {
309 userActiveEvents = false;
310 $(document).off( '.wp-heartbeat-active' );
311 $('iframe').each( function( i, frame ) {
312 if ( ! isLocalFrame( frame ) )
315 $( frame.contentWindow ).off( '.wp-heartbeat-active' );
321 // Set 'hasFocus = true' if user is active and the window is in the background.
322 // Set 'hasFocus = false' if the user has been inactive (no mouse or keyboard activity) for 5 min. even when the window has focus.
323 function checkUserActive() {
324 var lastActive = isUserActive ? time() - isUserActive : 0;
326 // Throttle down when no mouse or keyboard activity for 5 min
327 if ( lastActive > 300000 && hasFocus )
330 if ( ! userActiveEvents ) {
331 $(document).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
333 $('iframe').each( function( i, frame ) {
334 if ( ! isLocalFrame( frame ) )
337 $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active', function(){ userIsActive(); } );
340 userActiveEvents = true;
344 // Check for user activity every 30 seconds.
345 window.setInterval( function(){ checkUserActive(); }, 30000 );
346 $(document).ready( function() {
347 // Start one tick (15 sec) after DOM ready
353 this.hasFocus = function() {
358 * Get/Set the interval
360 * When setting to 'fast', the interval is 5 sec. for the next 30 ticks (for 2 min and 30 sec).
361 * If the window doesn't have focus, the interval slows down to 2 min.
363 * @param string speed Interval speed: 'fast' (5sec), 'standard' (15sec) default, 'slow' (60sec)
364 * @param string ticks Used with speed = 'fast', how many ticks before the speed reverts back
365 * @return int Current interval in seconds
367 this.interval = function( speed, ticks ) {
369 ticks = parseInt( ticks, 10 ) || 30;
370 ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
383 // Allow long polling, (experimental)
392 // Reset when the new interval value is lower than the current one
393 reset = seconds * 1000 < interval;
395 if ( countdown > 0 ) {
396 tempInterval = seconds * 1000;
398 interval = seconds * 1000;
409 return tempInterval ? tempInterval / 1000 : interval / 1000;
413 * Enqueue data to send with the next XHR
415 * As the data is sent later, this function doesn't return the XHR response.
416 * To see the response, use the custom jQuery event 'heartbeat-tick' on the document, example:
417 * $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
420 * If the same 'handle' is used more than once, the data is not overwritten when the third argument is 'true'.
421 * Use wp.heartbeat.isQueued('handle') to see if any data is already queued for that handle.
423 * $param string handle Unique handle for the data. The handle is used in PHP to receive the data.
424 * $param mixed data The data to send.
425 * $param bool dont_overwrite Whether to overwrite existing data in the queue.
426 * $return bool Whether the data was queued or not.
428 this.enqueue = function( handle, data, dont_overwrite ) {
430 if ( queue.hasOwnProperty( handle ) && dont_overwrite )
433 queue[handle] = data;
440 * Check if data with a particular handle is queued
442 * $param string handle The handle for the data
443 * $return mixed The data queued with that handle or null
445 this.isQueued = function( handle ) {
446 return queue[handle];
450 $.extend( Heartbeat.prototype, {
451 tick: function( data, textStatus, jqXHR ) {
452 $(document).trigger( 'heartbeat-tick', [data, textStatus, jqXHR] );
454 error: function( jqXHR, textStatus, error ) {
455 $(document).trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
459 wp.heartbeat = new Heartbeat();