smash-usage-session.js
45 lines
| 1 | /** |
| 2 | * Smash Usage Tracking: reports admin session duration on page unload. |
| 3 | * |
| 4 | * @package SmashBalloon\Reviews |
| 5 | */ |
| 6 | (function ($) { |
| 7 | 'use strict'; |
| 8 | |
| 9 | if (typeof window.sbrSmashUsageSession === 'undefined') { |
| 10 | return; |
| 11 | } |
| 12 | |
| 13 | var config = window.sbrSmashUsageSession; |
| 14 | var sessionStart = Date.now(); |
| 15 | var sessionSent = false; |
| 16 | |
| 17 | function sendSessionDuration() { |
| 18 | var durationSeconds = Math.round((Date.now() - sessionStart) / 1000); |
| 19 | if (sessionSent || durationSeconds < 3) { |
| 20 | return; |
| 21 | } |
| 22 | sessionSent = true; |
| 23 | if (navigator.sendBeacon) { |
| 24 | var data = new FormData(); |
| 25 | data.append('action', 'sbr_smash_usage_record_session'); |
| 26 | data.append('nonce', config.nonce); |
| 27 | data.append('duration_seconds', durationSeconds); |
| 28 | navigator.sendBeacon(config.ajax_url, data); |
| 29 | } else { |
| 30 | $.post(config.ajax_url, { |
| 31 | action: 'sbr_smash_usage_record_session', |
| 32 | nonce: config.nonce, |
| 33 | duration_seconds: durationSeconds |
| 34 | }); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | // pagehide is the reliable unload signal (beforeunload doesn't fire for |
| 39 | // beacons on mobile Safari); the sessionSent flag guards the fallback. |
| 40 | var unloadEvent = 'onpagehide' in window ? 'pagehide' : 'beforeunload'; |
| 41 | $(window).on(unloadEvent, function () { |
| 42 | sendSessionDuration(); |
| 43 | }); |
| 44 | })(jQuery); |
| 45 |