1monitor_client = { 2 init: function() { 3 4 /* send the page view request: */ 5 this._onPageView(this._src.replace( this._scriptName, '/pview.php')); 6 7 /* send the first heartbeat signal after x seconds: */ 8 setTimeout(this._onHeartbeat.bind(this, this._src.replace( this._scriptName, '/tick.php')),this._heartbeat * 1000); 9 }, 10 11 /* keep a reference to the script URL: */ 12 _src: document.currentScript.src, 13 14 /* heartbeat signal every x seconds: */ 15 _heartbeat: 30, 16 17 /* name of this script (with slash): */ 18 _scriptName: '/client.js', 19 20 /* function to init page data on server: */ 21 _onPageView: async function(url) { 22 try { 23 /* collect the data to send: */ 24 const visit = { 25 'pg': JSINFO.id, 26 'u': document._monitor.user || null, 27 'lg': navigator.language, 28 'lt': ( document._monitor ? Date.now() - document._monitor.t0 : null), 29 'r': document.referrer /*, 30 'tz': new Date().getTimezoneOffset(), 31 'url': window.location.href, 32 'scr': screen.width+':'+screen.height, 33 'l': navigator.languages */ 34 } 35 36 /* compile to a FormData object: */ 37 const data = new FormData(); 38 data.append( "pageview", JSON.stringify( visit ) ); 39 40 /* send the request */ 41 const response = await fetch(url + '?t=' + Date.now(), { 42 method: 'POST', 43 body: data 44 }); 45 if (!response.ok) { 46 throw new Error(response.status + ' ' + response.statusText + ' - ' + url); 47 } 48 } catch (err) { 49 console.error('Error: ', err); 50 } 51 }, 52 53 /* function to call regularly to show the user is still on the page: */ 54 _onHeartbeat: async function(url) { 55 //console.info('monitor_client._onHeartbeat', url); 56 57 try { 58 const response = await fetch(url + '?p=' + encodeURIComponent(JSINFO.id) + '&t=' + Date.now(), { 59 //method: 'HEAD', 60 }); 61 if (!response.ok) { 62 throw new Error(response.status + ' ' + response.statusText + ' - ' + url); 63 } 64 } catch (err) { 65 console.error(err); 66 } finally { 67 /* send the next heartbeat signal after x seconds: */ 68 setTimeout(this._onHeartbeat.bind(this, this._src.replace( this._scriptName, '/tick.php')),this._heartbeat * 1000); 69 } 70 } 71} 72 73// init the script: 74monitor_client.init();