You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

906 lines
23 KiB

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