-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbeacon.js
More file actions
237 lines (212 loc) · 9.27 KB
/
beacon.js
File metadata and controls
237 lines (212 loc) · 9.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
/**
* CloudScale Page Views - beacon.js v3.0.0
*
* MODE: 'record' (singular post/page)
* Single POST to record the view. The response contains the updated
* count which is stored in window.cspvViews and used to update any
* .cspv-views-count elements on the page.
* NO second API call is made — the record response IS the count.
*
* MODE: 'fetch' (home / archive / search listing pages)
* Does NOT increment anything. Reads [data-cspv-id] attributes from
* the DOM, fetches all counts in one GET, injects them back.
*
* THEME INTEGRATION
* -----------------
* Single post template — just call the PHP helper, nothing else needed:
* <?php cspv_the_views(); ?>
*
* Archive/listing template — add data-cspv-id to your count element:
* <span class="cspv-views-count" data-cspv-id="<?php the_ID(); ?>">
* <?php echo cspv_get_view_count(); ?>
* </span>
*
* The beacon handles both automatically. You never need both on the
* same page — on singular pages data-cspv-id is ignored in favour of
* the record response.
*/
( function () {
'use strict';
if ( typeof cspvData === 'undefined' ) { return; }
var debug = cspvData.debug === true;
var postId = cspvData.postId ? String( cspvData.postId ) : null;
// ------------------------------------------------------------------
// Session ID — persists for the lifetime of the browser tab via
// sessionStorage. Scoped to the tab so a new session starts when
// the tab is closed and reopened, exactly like a traditional session.
// Contains no PII.
// ------------------------------------------------------------------
function getSessionId() {
try {
var k = 'cspv_sid';
var sid = sessionStorage.getItem( k );
if ( ! sid ) {
sid = Math.random().toString( 36 ).slice( 2 ) +
Math.random().toString( 36 ).slice( 2 );
sessionStorage.setItem( k, sid );
}
return sid;
} catch ( e ) { return ''; }
}
function log() {
if ( debug && typeof console !== 'undefined' ) {
console.log.apply( console, ['[CloudScale PV]'].concat(
Array.prototype.slice.call( arguments ) ) );
}
}
// ------------------------------------------------------------------
// Update DOM elements with a counts map { "postId": count, ... }
// ------------------------------------------------------------------
function updateDOM( counts ) {
Object.keys( counts ).forEach( function( id ) {
var val = Number( counts[ id ] ).toLocaleString();
// Archive-style elements with explicit data-cspv-id
document.querySelectorAll( '[data-cspv-id="' + id + '"]' )
.forEach( function( el ) { el.textContent = val; } );
} );
// On singular pages also update plain .cspv-views-count elements
// (the ones output by cspv_the_views() with no data-cspv-id)
if ( cspvData.mode === 'record' && postId && counts[ postId ] !== undefined ) {
var val = Number( counts[ postId ] ).toLocaleString();
document.querySelectorAll( '.cspv-views-count:not([data-cspv-id])' )
.forEach( function( el ) { el.textContent = val; } );
// Also update auto-display counters
document.querySelectorAll( '.cspv-ad-num' )
.forEach( function( el ) { el.textContent = val; } );
// Expose as a global so advanced templates can read it
window.cspvViews = counts[ postId ];
log( 'window.cspvViews set to', window.cspvViews );
}
}
// ------------------------------------------------------------------
// MODE: record
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// Deduplication via localStorage with 24 hour TTL
// Unlike sessionStorage, localStorage persists across tabs and
// browser restarts, preventing double counts when a link opens
// first in an in app browser (WhatsApp, Facebook, etc.) and then
// again in a real browser tab on the same device.
// ------------------------------------------------------------------
var DEDUP_TTL_MS = 24 * 60 * 60 * 1000; // 24 hours
function isDuplicate( pid ) {
try {
var raw = localStorage.getItem( 'cspv_seen_' + pid );
if ( ! raw ) { return false; }
var ts = parseInt( raw, 10 );
if ( isNaN( ts ) ) { return false; }
if ( Date.now() - ts > DEDUP_TTL_MS ) {
localStorage.removeItem( 'cspv_seen_' + pid );
return false;
}
return true;
} catch(e) { return false; } // localStorage blocked — allow recording
}
function markSeen( pid ) {
try { localStorage.setItem( 'cspv_seen_' + pid, String( Date.now() ) ); } catch(e) {}
}
// Prune expired dedup keys periodically (max once per page load)
function pruneDedup() {
try {
var now = Date.now();
var i = localStorage.length;
while ( i-- ) {
var key = localStorage.key( i );
if ( key && key.indexOf( 'cspv_seen_' ) === 0 ) {
var ts = parseInt( localStorage.getItem( key ), 10 );
if ( isNaN( ts ) || now - ts > DEDUP_TTL_MS ) {
localStorage.removeItem( key );
}
}
}
} catch(e) {}
}
pruneDedup();
function recordView() {
log( 'record mode — post', postId );
// Deduplicate: only record once per 24 hours per post per browser
// Respects the server-side dedup setting — when dedup is off, always record
// wp_localize_script converts booleans: true -> "1", false -> ""
var dedupOn = !!cspvData.dedupOn && cspvData.dedupOn !== '0' && cspvData.dedupOn !== '';
if ( dedupOn && isDuplicate( postId ) ) {
log( 'already recorded within 24h — skipping beacon, fetching count' );
// Still fetch the current count so the display stays fresh
fetch( cspvData.apiUrl.replace( '/record/' + postId, '/counts?ids=' + postId ), {
method: 'GET', credentials: 'same-origin'
} )
.then( function( r ) { return r.ok ? r.json() : null; } )
.then( function( counts ) { if ( counts ) updateDOM( counts ); } )
.catch( function() {} );
return;
}
fetch( cspvData.apiUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cspvData.nonce },
body: JSON.stringify( { referrer: document.referrer || '', session_id: getSessionId() } ),
credentials: 'same-origin',
keepalive: true,
} )
.then( function( r ) {
if ( ! r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function( data ) {
if ( ! data || data.views === undefined ) { return; }
log( 'recorded. count now:', data.views, '| logged:', data.logged );
var counts = {};
counts[ postId ] = data.views;
updateDOM( counts );
// Mark as seen for 24 hours (only when dedup is enabled)
if ( dedupOn ) { markSeen( postId ); }
} )
.catch( function( err ) { log( 'beacon error:', err ); } );
}
// ------------------------------------------------------------------
// MODE: fetch (archive / listing)
// ------------------------------------------------------------------
function fetchCounts() {
var els = document.querySelectorAll( '[data-cspv-id]' );
var ids = [];
var seen = {};
els.forEach( function( el ) {
var id = el.getAttribute( 'data-cspv-id' );
if ( id && ! seen[ id ] ) { ids.push( id ); seen[ id ] = true; }
} );
if ( ids.length === 0 ) {
log( 'fetch mode — no [data-cspv-id] elements found.' );
return;
}
log( 'fetch mode — fetching counts for', ids.length, 'posts' );
fetch( cspvData.countsUrl + '?ids=' + ids.join( ',' ), {
method: 'GET', credentials: 'same-origin',
} )
.then( function( r ) {
if ( ! r.ok ) { throw new Error( 'HTTP ' + r.status ); }
return r.json();
} )
.then( function( counts ) {
if ( ! counts ) { return; }
log( 'received counts:', counts );
updateDOM( counts );
} )
.catch( function( err ) { log( 'fetch error:', err ); } );
}
// ------------------------------------------------------------------
// Boot (guarded against double execution)
// ------------------------------------------------------------------
var booted = false;
function boot() {
if ( booted ) { return; }
booted = true;
if ( cspvData.mode === 'record' ) {
recordView();
} else {
fetchCounts();
}
}
if ( document.readyState === 'complete' ) {
boot();
} else {
window.addEventListener( 'load', boot );
}
} )();