JSFiddle - React, Tailwind, and code Playground
HTML
<button>
Pretend to leave page...
</button>
<div>
</div>
JavaScript
var load = new Date();
$('button').click(function() {
var leave = new Date();
var duration = (leave.getTime() - load.getTime()) / 1000;
var counted_time = parseFloat(readCookie('time_spent')) || 0;
var time_spent = counted_time + duration
createCookie('time_spent', time_spent);
// The below lines are only for this example.
// They are not needed when using onbeforeunload
$('div').append('<p>visited for ' + time_spent + ' seconds</p>');
load = new Date();
});
function createCookie(name, value) {
document.cookie = name + "=" + value + "; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}