[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/js/ -> heartbeat.js (source)

   1  /**
   2   * Heartbeat API
   3   *
   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.
   8   *
   9   * Available PHP filters (in ajax-actions.php):
  10   * - heartbeat_received
  11   * - heartbeat_send
  12   * - heartbeat_tick
  13   * - heartbeat_nopriv_received
  14   * - heartbeat_nopriv_send
  15   * - heartbeat_nopriv_tick
  16   * @see wp_ajax_nopriv_heartbeat(), wp_ajax_heartbeat()
  17   *
  18   * Custom jQuery events:
  19   * - heartbeat-send
  20   * - heartbeat-tick
  21   * - heartbeat-error
  22   * - heartbeat-connection-lost
  23   * - heartbeat-connection-restored
  24   * - heartbeat-nonces-expired
  25   *
  26   * @since 3.6.0
  27   * @output wp-includes/js/heartbeat.js
  28   */
  29  
  30  ( function( $, window, undefined ) {
  31  
  32      /**
  33       * Constructs the Heartbeat API.
  34       *
  35       * @since 3.6.0
  36       *
  37       * @return {Object} An instance of the Heartbeat class.
  38       * @constructor
  39       */
  40      var Heartbeat = function() {
  41          var $document = $(document),
  42              settings = {
  43                  // Suspend/resume.
  44                  suspend: false,
  45  
  46                  // Whether suspending is enabled.
  47                  suspendEnabled: true,
  48  
  49                  // Current screen id, defaults to the JS global 'pagenow' when present
  50                  // (in the admin) or 'front'.
  51                  screenId: '',
  52  
  53                  // XHR request URL, defaults to the JS global 'ajaxurl' when present.
  54                  url: '',
  55  
  56                  // Timestamp, start of the last connection request.
  57                  lastTick: 0,
  58  
  59                  // Container for the enqueued items.
  60                  queue: {},
  61  
  62                  // Connect interval (in seconds).
  63                  mainInterval: 60,
  64  
  65                  // Used when the interval is set to 5 seconds temporarily.
  66                  tempInterval: 0,
  67  
  68                  // Used when the interval is reset.
  69                  originalInterval: 0,
  70  
  71                  // Used to limit the number of Ajax requests.
  72                  minimalInterval: 0,
  73  
  74                  // Used together with tempInterval.
  75                  countdown: 0,
  76  
  77                  // Whether a connection is currently in progress.
  78                  connecting: false,
  79  
  80                  // Whether a connection error occurred.
  81                  connectionError: false,
  82  
  83                  // Used to track non-critical errors.
  84                  errorcount: 0,
  85  
  86                  // Whether at least one connection has been completed successfully.
  87                  hasConnected: false,
  88  
  89                  // Whether the current browser window is in focus and the user is active.
  90                  hasFocus: true,
  91  
  92                  // Timestamp, last time the user was active. Checked every 30 seconds.
  93                  userActivity: 0,
  94  
  95                  // Flag whether events tracking user activity were set.
  96                  userActivityEvents: false,
  97  
  98                  // Timer that keeps track of how long a user has focus.
  99                  checkFocusTimer: 0,
 100  
 101                  // Timer that keeps track of how long needs to be waited before connecting to
 102                  // the server again.
 103                  beatTimer: 0
 104              };
 105  
 106          /**
 107           * Sets local variables and events, then starts the heartbeat.
 108           *
 109           * @since 3.8.0
 110           * @access private
 111           *
 112           * @return {void}
 113           */
 114  		function initialize() {
 115              var options, hidden, visibilityState, visibilitychange;
 116  
 117              if ( typeof window.pagenow === 'string' ) {
 118                  settings.screenId = window.pagenow;
 119              }
 120  
 121              if ( typeof window.ajaxurl === 'string' ) {
 122                  settings.url = window.ajaxurl;
 123              }
 124  
 125              // Pull in options passed from PHP.
 126              if ( typeof window.heartbeatSettings === 'object' ) {
 127                  options = window.heartbeatSettings;
 128  
 129                  // The XHR URL can be passed as option when window.ajaxurl is not set.
 130                  if ( ! settings.url && options.ajaxurl ) {
 131                      settings.url = options.ajaxurl;
 132                  }
 133  
 134                  /*
 135                   * The interval can be from 15 to 120 seconds and can be set temporarily to 5 seconds.
 136                   * It can be set in the initial options or changed later through JS and/or through PHP.
 137                   */
 138                  if ( options.interval ) {
 139                      settings.mainInterval = options.interval;
 140  
 141                      if ( settings.mainInterval < 15 ) {
 142                          settings.mainInterval = 15;
 143                      } else if ( settings.mainInterval > 120 ) {
 144                          settings.mainInterval = 120;
 145                      }
 146                  }
 147  
 148                  /*
 149                   * Used to limit the number of Ajax requests. Overrides all other intervals
 150                   * if they are shorter. Needed for some hosts that cannot handle frequent requests
 151                   * and the user may exceed the allocated server CPU time, etc. The minimal interval
 152                   * can be up to 600 seconds, however setting it to longer than 120 seconds
 153                   * will limit or disable some of the functionality (like post locks).
 154                   * Once set at initialization, minimalInterval cannot be changed/overridden.
 155                   */
 156                  if ( options.minimalInterval ) {
 157                      options.minimalInterval = parseInt( options.minimalInterval, 10 );
 158                      settings.minimalInterval = options.minimalInterval > 0 && options.minimalInterval <= 600 ? options.minimalInterval : 0;
 159                  }
 160  
 161                  if ( settings.minimalInterval && settings.mainInterval < settings.minimalInterval ) {
 162                      settings.mainInterval = settings.minimalInterval;
 163                  }
 164  
 165                  // 'screenId' can be added from settings on the front end where the JS global
 166                  // 'pagenow' is not set.
 167                  if ( ! settings.screenId ) {
 168                      settings.screenId = options.screenId || 'front';
 169                  }
 170  
 171                  if ( options.suspension === 'disable' ) {
 172                      settings.suspendEnabled = false;
 173                  }
 174              }
 175  
 176              // Convert to milliseconds.
 177              settings.mainInterval = settings.mainInterval * 1000;
 178              settings.originalInterval = settings.mainInterval;
 179              if ( settings.minimalInterval ) {
 180                  settings.minimalInterval = settings.minimalInterval * 1000;
 181              }
 182  
 183              /*
 184               * Switch the interval to 120 seconds by using the Page Visibility API.
 185               * If the browser doesn't support it (Safari < 7, Android < 4.4, IE < 10), the
 186               * interval will be increased to 120 seconds after 5 minutes of mouse and keyboard
 187               * inactivity.
 188               */
 189              if ( typeof document.hidden !== 'undefined' ) {
 190                  hidden = 'hidden';
 191                  visibilitychange = 'visibilitychange';
 192                  visibilityState = 'visibilityState';
 193              } else if ( typeof document.msHidden !== 'undefined' ) { // IE10.
 194                  hidden = 'msHidden';
 195                  visibilitychange = 'msvisibilitychange';
 196                  visibilityState = 'msVisibilityState';
 197              } else if ( typeof document.webkitHidden !== 'undefined' ) { // Android.
 198                  hidden = 'webkitHidden';
 199                  visibilitychange = 'webkitvisibilitychange';
 200                  visibilityState = 'webkitVisibilityState';
 201              }
 202  
 203              if ( hidden ) {
 204                  if ( document[hidden] ) {
 205                      settings.hasFocus = false;
 206                  }
 207  
 208                  $document.on( visibilitychange + '.wp-heartbeat', function() {
 209                      if ( document[visibilityState] === 'hidden' ) {
 210                          blurred();
 211                          window.clearInterval( settings.checkFocusTimer );
 212                      } else {
 213                          focused();
 214                          if ( document.hasFocus ) {
 215                              settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
 216                          }
 217                      }
 218                  });
 219              }
 220  
 221              // Use document.hasFocus() if available.
 222              if ( document.hasFocus ) {
 223                  settings.checkFocusTimer = window.setInterval( checkFocus, 10000 );
 224              }
 225  
 226              $(window).on( 'unload.wp-heartbeat', function() {
 227                  // Don't connect anymore.
 228                  settings.suspend = true;
 229  
 230                  // Abort the last request if not completed.
 231                  if ( settings.xhr && settings.xhr.readyState !== 4 ) {
 232                      settings.xhr.abort();
 233                  }
 234              });
 235  
 236              // Check for user activity every 30 seconds.
 237              window.setInterval( checkUserActivity, 30000 );
 238  
 239              // Start one tick after DOM ready.
 240              $( function() {
 241                  settings.lastTick = time();
 242                  scheduleNextTick();
 243              });
 244          }
 245  
 246          /**
 247           * Returns the current time according to the browser.
 248           *
 249           * @since 3.6.0
 250           * @access private
 251           *
 252           * @return {number} Returns the current time.
 253           */
 254  		function time() {
 255              return (new Date()).getTime();
 256          }
 257  
 258          /**
 259           * Checks if the iframe is from the same origin.
 260           *
 261           * @since 3.6.0
 262           * @access private
 263           *
 264           * @return {boolean} Returns whether or not the iframe is from the same origin.
 265           */
 266  		function isLocalFrame( frame ) {
 267              var origin, src = frame.src;
 268  
 269              /*
 270               * Need to compare strings as WebKit doesn't throw JS errors when iframes have
 271               * different origin. It throws uncatchable exceptions.
 272               */
 273              if ( src && /^https?:\/\//.test( src ) ) {
 274                  origin = window.location.origin ? window.location.origin : window.location.protocol + '//' + window.location.host;
 275  
 276                  if ( src.indexOf( origin ) !== 0 ) {
 277                      return false;
 278                  }
 279              }
 280  
 281              try {
 282                  if ( frame.contentWindow.document ) {
 283                      return true;
 284                  }
 285              } catch(e) {}
 286  
 287              return false;
 288          }
 289  
 290          /**
 291           * Checks if the document's focus has changed.
 292           *
 293           * @since 4.1.0
 294           * @access private
 295           *
 296           * @return {void}
 297           */
 298  		function checkFocus() {
 299              if ( settings.hasFocus && ! document.hasFocus() ) {
 300                  blurred();
 301              } else if ( ! settings.hasFocus && document.hasFocus() ) {
 302                  focused();
 303              }
 304          }
 305  
 306          /**
 307           * Sets error state and fires an event on XHR errors or timeout.
 308           *
 309           * @since 3.8.0
 310           * @access private
 311           *
 312           * @param {string} error  The error type passed from the XHR.
 313           * @param {number} status The HTTP status code passed from jqXHR
 314           *                        (200, 404, 500, etc.).
 315           *
 316           * @return {void}
 317           */
 318  		function setErrorState( error, status ) {
 319              var trigger;
 320  
 321              if ( error ) {
 322                  switch ( error ) {
 323                      case 'abort':
 324                          // Do nothing.
 325                          break;
 326                      case 'timeout':
 327                          // No response for 30 seconds.
 328                          trigger = true;
 329                          break;
 330                      case 'error':
 331                          if ( 503 === status && settings.hasConnected ) {
 332                              trigger = true;
 333                              break;
 334                          }
 335                          /* falls through */
 336                      case 'parsererror':
 337                      case 'empty':
 338                      case 'unknown':
 339                          settings.errorcount++;
 340  
 341                          if ( settings.errorcount > 2 && settings.hasConnected ) {
 342                              trigger = true;
 343                          }
 344  
 345                          break;
 346                  }
 347  
 348                  if ( trigger && ! hasConnectionError() ) {
 349                      settings.connectionError = true;
 350                      $document.trigger( 'heartbeat-connection-lost', [error, status] );
 351                      wp.hooks.doAction( 'heartbeat.connection-lost', error, status );
 352                  }
 353              }
 354          }
 355  
 356          /**
 357           * Clears the error state and fires an event if there is a connection error.
 358           *
 359           * @since 3.8.0
 360           * @access private
 361           *
 362           * @return {void}
 363           */
 364  		function clearErrorState() {
 365              // Has connected successfully.
 366              settings.hasConnected = true;
 367  
 368              if ( hasConnectionError() ) {
 369                  settings.errorcount = 0;
 370                  settings.connectionError = false;
 371                  $document.trigger( 'heartbeat-connection-restored' );
 372                  wp.hooks.doAction( 'heartbeat.connection-restored' );
 373              }
 374          }
 375  
 376          /**
 377           * Gathers the data and connects to the server.
 378           *
 379           * @since 3.6.0
 380           * @access private
 381           *
 382           * @return {void}
 383           */
 384  		function connect() {
 385              var ajaxData, heartbeatData;
 386  
 387              // If the connection to the server is slower than the interval,
 388              // heartbeat connects as soon as the previous connection's response is received.
 389              if ( settings.connecting || settings.suspend ) {
 390                  return;
 391              }
 392  
 393              settings.lastTick = time();
 394  
 395              heartbeatData = $.extend( {}, settings.queue );
 396              // Clear the data queue. Anything added after this point will be sent on the next tick.
 397              settings.queue = {};
 398  
 399              $document.trigger( 'heartbeat-send', [ heartbeatData ] );
 400              wp.hooks.doAction( 'heartbeat.send', heartbeatData );
 401  
 402              ajaxData = {
 403                  data: heartbeatData,
 404                  interval: settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000,
 405                  _nonce: typeof window.heartbeatSettings === 'object' ? window.heartbeatSettings.nonce : '',
 406                  action: 'heartbeat',
 407                  screen_id: settings.screenId,
 408                  has_focus: settings.hasFocus
 409              };
 410  
 411              if ( 'customize' === settings.screenId  ) {
 412                  ajaxData.wp_customize = 'on';
 413              }
 414  
 415              settings.connecting = true;
 416              settings.xhr = $.ajax({
 417                  url: settings.url,
 418                  type: 'post',
 419                  timeout: 30000, // Throw an error if not completed after 30 seconds.
 420                  data: ajaxData,
 421                  dataType: 'json'
 422              }).always( function() {
 423                  settings.connecting = false;
 424                  scheduleNextTick();
 425              }).done( function( response, textStatus, jqXHR ) {
 426                  var newInterval;
 427  
 428                  if ( ! response ) {
 429                      setErrorState( 'empty' );
 430                      return;
 431                  }
 432  
 433                  clearErrorState();
 434  
 435                  if ( response.nonces_expired ) {
 436                      $document.trigger( 'heartbeat-nonces-expired' );
 437                      wp.hooks.doAction( 'heartbeat.nonces-expired' );
 438                  }
 439  
 440                  // Change the interval from PHP.
 441                  if ( response.heartbeat_interval ) {
 442                      newInterval = response.heartbeat_interval;
 443                      delete response.heartbeat_interval;
 444                  }
 445  
 446                  // Update the heartbeat nonce if set.
 447                  if ( response.heartbeat_nonce && typeof window.heartbeatSettings === 'object' ) {
 448                      window.heartbeatSettings.nonce = response.heartbeat_nonce;
 449                      delete response.heartbeat_nonce;
 450                  }
 451  
 452                  // Update the Rest API nonce if set and wp-api loaded.
 453                  if ( response.rest_nonce && typeof window.wpApiSettings === 'object' ) {
 454                      window.wpApiSettings.nonce = response.rest_nonce;
 455                      // This nonce is required for api-fetch through heartbeat.tick.
 456                      // delete response.rest_nonce;
 457                  }
 458  
 459                  $document.trigger( 'heartbeat-tick', [response, textStatus, jqXHR] );
 460                  wp.hooks.doAction( 'heartbeat.tick', response, textStatus, jqXHR );
 461  
 462                  // Do this last. Can trigger the next XHR if connection time > 5 seconds and newInterval == 'fast'.
 463                  if ( newInterval ) {
 464                      interval( newInterval );
 465                  }
 466              }).fail( function( jqXHR, textStatus, error ) {
 467                  setErrorState( textStatus || 'unknown', jqXHR.status );
 468                  $document.trigger( 'heartbeat-error', [jqXHR, textStatus, error] );
 469                  wp.hooks.doAction( 'heartbeat.error', jqXHR, textStatus, error );
 470              });
 471          }
 472  
 473          /**
 474           * Schedules the next connection.
 475           *
 476           * Fires immediately if the connection time is longer than the interval.
 477           *
 478           * @since 3.8.0
 479           * @access private
 480           *
 481           * @return {void}
 482           */
 483  		function scheduleNextTick() {
 484              var delta = time() - settings.lastTick,
 485                  interval = settings.mainInterval;
 486  
 487              if ( settings.suspend ) {
 488                  return;
 489              }
 490  
 491              if ( ! settings.hasFocus ) {
 492                  interval = 120000; // 120 seconds. Post locks expire after 150 seconds.
 493              } else if ( settings.countdown > 0 && settings.tempInterval ) {
 494                  interval = settings.tempInterval;
 495                  settings.countdown--;
 496  
 497                  if ( settings.countdown < 1 ) {
 498                      settings.tempInterval = 0;
 499                  }
 500              }
 501  
 502              if ( settings.minimalInterval && interval < settings.minimalInterval ) {
 503                  interval = settings.minimalInterval;
 504              }
 505  
 506              window.clearTimeout( settings.beatTimer );
 507  
 508              if ( delta < interval ) {
 509                  settings.beatTimer = window.setTimeout(
 510                      function() {
 511                          connect();
 512                      },
 513                      interval - delta
 514                  );
 515              } else {
 516                  connect();
 517              }
 518          }
 519  
 520          /**
 521           * Sets the internal state when the browser window becomes hidden or loses focus.
 522           *
 523           * @since 3.6.0
 524           * @access private
 525           *
 526           * @return {void}
 527           */
 528  		function blurred() {
 529              settings.hasFocus = false;
 530          }
 531  
 532          /**
 533           * Sets the internal state when the browser window becomes visible or is in focus.
 534           *
 535           * @since 3.6.0
 536           * @access private
 537           *
 538           * @return {void}
 539           */
 540  		function focused() {
 541              settings.userActivity = time();
 542  
 543              // Resume if suspended.
 544              settings.suspend = false;
 545  
 546              if ( ! settings.hasFocus ) {
 547                  settings.hasFocus = true;
 548                  scheduleNextTick();
 549              }
 550          }
 551  
 552          /**
 553           * Runs when the user becomes active after a period of inactivity.
 554           *
 555           * @since 3.6.0
 556           * @access private
 557           *
 558           * @return {void}
 559           */
 560  		function userIsActive() {
 561              settings.userActivityEvents = false;
 562              $document.off( '.wp-heartbeat-active' );
 563  
 564              $('iframe').each( function( i, frame ) {
 565                  if ( isLocalFrame( frame ) ) {
 566                      $( frame.contentWindow ).off( '.wp-heartbeat-active' );
 567                  }
 568              });
 569  
 570              focused();
 571          }
 572  
 573          /**
 574           * Checks for user activity.
 575           *
 576           * Runs every 30 seconds. Sets 'hasFocus = true' if user is active and the window
 577           * is in the background. Sets 'hasFocus = false' if the user has been inactive
 578           * (no mouse or keyboard activity) for 5 minutes even when the window has focus.
 579           *
 580           * @since 3.8.0
 581           * @access private
 582           *
 583           * @return {void}
 584           */
 585  		function checkUserActivity() {
 586              var lastActive = settings.userActivity ? time() - settings.userActivity : 0;
 587  
 588              // Throttle down when no mouse or keyboard activity for 5 minutes.
 589              if ( lastActive > 300000 && settings.hasFocus ) {
 590                  blurred();
 591              }
 592  
 593              // Suspend after 10 minutes of inactivity when suspending is enabled.
 594              // Always suspend after 60 minutes of inactivity. This will release the post lock, etc.
 595              if ( ( settings.suspendEnabled && lastActive > 600000 ) || lastActive > 3600000 ) {
 596                  settings.suspend = true;
 597              }
 598  
 599              if ( ! settings.userActivityEvents ) {
 600                  $document.on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
 601                      userIsActive();
 602                  });
 603  
 604                  $('iframe').each( function( i, frame ) {
 605                      if ( isLocalFrame( frame ) ) {
 606                          $( frame.contentWindow ).on( 'mouseover.wp-heartbeat-active keyup.wp-heartbeat-active touchend.wp-heartbeat-active', function() {
 607                              userIsActive();
 608                          });
 609                      }
 610                  });
 611  
 612                  settings.userActivityEvents = true;
 613              }
 614          }
 615  
 616          // Public methods.
 617  
 618          /**
 619           * Checks whether the window (or any local iframe in it) has focus, or the user
 620           * is active.
 621           *
 622           * @since 3.6.0
 623           * @memberOf wp.heartbeat.prototype
 624           *
 625           * @return {boolean} True if the window or the user is active.
 626           */
 627  		function hasFocus() {
 628              return settings.hasFocus;
 629          }
 630  
 631          /**
 632           * Checks whether there is a connection error.
 633           *
 634           * @since 3.6.0
 635           *
 636           * @memberOf wp.heartbeat.prototype
 637           *
 638           * @return {boolean} True if a connection error was found.
 639           */
 640  		function hasConnectionError() {
 641              return settings.connectionError;
 642          }
 643  
 644          /**
 645           * Connects as soon as possible regardless of 'hasFocus' state.
 646           *
 647           * Will not open two concurrent connections. If a connection is in progress,
 648           * will connect again immediately after the current connection completes.
 649           *
 650           * @since 3.8.0
 651           *
 652           * @memberOf wp.heartbeat.prototype
 653           *
 654           * @return {void}
 655           */
 656  		function connectNow() {
 657              settings.lastTick = 0;
 658              scheduleNextTick();
 659          }
 660  
 661          /**
 662           * Disables suspending.
 663           *
 664           * Should be used only when Heartbeat is performing critical tasks like
 665           * autosave, post-locking, etc. Using this on many screens may overload
 666           * the user's hosting account if several browser windows/tabs are left open
 667           * for a long time.
 668           *
 669           * @since 3.8.0
 670           *
 671           * @memberOf wp.heartbeat.prototype
 672           *
 673           * @return {void}
 674           */
 675  		function disableSuspend() {
 676              settings.suspendEnabled = false;
 677          }
 678  
 679          /**
 680           * Gets/Sets the interval.
 681           *
 682           * When setting to 'fast' or 5, the interval is 5 seconds for the next 30 ticks
 683           * (for 2 minutes and 30 seconds) by default. In this case the number of 'ticks'
 684           * can be passed as second argument. If the window doesn't have focus,
 685           * the interval slows down to 2 minutes.
 686           *
 687           * @since 3.6.0
 688           *
 689           * @memberOf wp.heartbeat.prototype
 690           *
 691           * @param {string|number} speed Interval: 'fast' or 5, 15, 30, 60, 120.
 692           *                              Fast equals 5.
 693           * @param {string}        ticks Tells how many ticks before the interval reverts
 694           *                              back. Used with speed = 'fast' or 5.
 695           *
 696           * @return {number} Current interval in seconds.
 697           */
 698  		function interval( speed, ticks ) {
 699              var newInterval,
 700                  oldInterval = settings.tempInterval ? settings.tempInterval : settings.mainInterval;
 701  
 702              if ( speed ) {
 703                  switch ( speed ) {
 704                      case 'fast':
 705                      case 5:
 706                          newInterval = 5000;
 707                          break;
 708                      case 15:
 709                          newInterval = 15000;
 710                          break;
 711                      case 30:
 712                          newInterval = 30000;
 713                          break;
 714                      case 60:
 715                          newInterval = 60000;
 716                          break;
 717                      case 120:
 718                          newInterval = 120000;
 719                          break;
 720                      case 'long-polling':
 721                          // Allow long polling (experimental).
 722                          settings.mainInterval = 0;
 723                          return 0;
 724                      default:
 725                          newInterval = settings.originalInterval;
 726                  }
 727  
 728                  if ( settings.minimalInterval && newInterval < settings.minimalInterval ) {
 729                      newInterval = settings.minimalInterval;
 730                  }
 731  
 732                  if ( 5000 === newInterval ) {
 733                      ticks = parseInt( ticks, 10 ) || 30;
 734                      ticks = ticks < 1 || ticks > 30 ? 30 : ticks;
 735  
 736                      settings.countdown = ticks;
 737                      settings.tempInterval = newInterval;
 738                  } else {
 739                      settings.countdown = 0;
 740                      settings.tempInterval = 0;
 741                      settings.mainInterval = newInterval;
 742                  }
 743  
 744                  /*
 745                   * Change the next connection time if new interval has been set.
 746                   * Will connect immediately if the time since the last connection
 747                   * is greater than the new interval.
 748                   */
 749                  if ( newInterval !== oldInterval ) {
 750                      scheduleNextTick();
 751                  }
 752              }
 753  
 754              return settings.tempInterval ? settings.tempInterval / 1000 : settings.mainInterval / 1000;
 755          }
 756  
 757          /**
 758           * Enqueues data to send with the next XHR.
 759           *
 760           * As the data is send asynchronously, this function doesn't return the XHR
 761           * response. To see the response, use the custom jQuery event 'heartbeat-tick'
 762           * on the document, example:
 763           *        $(document).on( 'heartbeat-tick.myname', function( event, data, textStatus, jqXHR ) {
 764           *            // code
 765           *        });
 766           * If the same 'handle' is used more than once, the data is not overwritten when
 767           * the third argument is 'true'. Use `wp.heartbeat.isQueued('handle')` to see if
 768           * any data is already queued for that handle.
 769           *
 770           * @since 3.6.0
 771           *
 772           * @memberOf wp.heartbeat.prototype
 773           *
 774           * @param {string}  handle      Unique handle for the data, used in PHP to
 775           *                              receive the data.
 776           * @param {*}       data        The data to send.
 777           * @param {boolean} noOverwrite Whether to overwrite existing data in the queue.
 778           *
 779           * @return {boolean} True if the data was queued.
 780           */
 781  		function enqueue( handle, data, noOverwrite ) {
 782              if ( handle ) {
 783                  if ( noOverwrite && this.isQueued( handle ) ) {
 784                      return false;
 785                  }
 786  
 787                  settings.queue[handle] = data;
 788                  return true;
 789              }
 790              return false;
 791          }
 792  
 793          /**
 794           * Checks if data with a particular handle is queued.
 795           *
 796           * @since 3.6.0
 797           *
 798           * @param {string} handle The handle for the data.
 799           *
 800           * @return {boolean} True if the data is queued with this handle.
 801           */
 802  		function isQueued( handle ) {
 803              if ( handle ) {
 804                  return settings.queue.hasOwnProperty( handle );
 805              }
 806          }
 807  
 808          /**
 809           * Removes data with a particular handle from the queue.
 810           *
 811           * @since 3.7.0
 812           *
 813           * @memberOf wp.heartbeat.prototype
 814           *
 815           * @param {string} handle The handle for the data.
 816           *
 817           * @return {void}
 818           */
 819  		function dequeue( handle ) {
 820              if ( handle ) {
 821                  delete settings.queue[handle];
 822              }
 823          }
 824  
 825          /**
 826           * Gets data that was enqueued with a particular handle.
 827           *
 828           * @since 3.7.0
 829           *
 830           * @memberOf wp.heartbeat.prototype
 831           *
 832           * @param {string} handle The handle for the data.
 833           *
 834           * @return {*} The data or undefined.
 835           */
 836  		function getQueuedItem( handle ) {
 837              if ( handle ) {
 838                  return this.isQueued( handle ) ? settings.queue[handle] : undefined;
 839              }
 840          }
 841  
 842          initialize();
 843  
 844          // Expose public methods.
 845          return {
 846              hasFocus: hasFocus,
 847              connectNow: connectNow,
 848              disableSuspend: disableSuspend,
 849              interval: interval,
 850              hasConnectionError: hasConnectionError,
 851              enqueue: enqueue,
 852              dequeue: dequeue,
 853              isQueued: isQueued,
 854              getQueuedItem: getQueuedItem
 855          };
 856      };
 857  
 858      /**
 859       * Ensure the global `wp` object exists.
 860       *
 861       * @namespace wp
 862       */
 863      window.wp = window.wp || {};
 864  
 865      /**
 866       * Contains the Heartbeat API.
 867       *
 868       * @namespace wp.heartbeat
 869       * @type {Heartbeat}
 870       */
 871      window.wp.heartbeat = new Heartbeat();
 872  
 873  }( jQuery, window ));


Generated: Sat Apr 20 01:00:03 2024 Cross-referenced by PHPXref 0.7.1