β¦ π 2 min, π 4 min
t_page_opened
t_page_closed
onload
Java Script event and determine that as the start of page visit with:window.onload = function () {
t_page_opened = new Date();
};
Now let's say that the user leaves the web page by closing the browser tab or browser window. We can detect that via beforeunload
event by adding the event listener:window.addEventListener("beforeunload", leftWebSite);
leftWebSite
function then get's the time stamp when user left the page:function leftWebSite() {
const t_page_closed = new Date();
const data = JSON.stringify({
"page_opened": t_page_opened,
"page_closed": t_page_closed
});
post_data(data, "define_URL");
}
and sends the t_page_opened
and t_page_closed
to the a prediefined URL
with post_data
function:function post_data(data, url) {
let xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log(xhr.responseText);
}
};
xhr.send(data);
}
Job done, right? Far from it.If we want to have a proper estimate of the read times, we need to be really careful about potential corner cases for page opening and page closing.Wait? Page view start and page view end should be determinable in a few lines of code. Not quite. beforeunload
won't get consistently triggered (from browser to browser). Let's list the cases we need to cover. When the user leaves the page via:beforeunload
. Solved.onclick
eventlocalStorage
if the user didn't clean it - the user never comes back to our site: data lostlocalStorage
pagehide
event, since page JS
won't be re-loaded and beforeunload
event won't be triggered.localStorage
won't work if the user:onload
. To handle the page left via history back, the forward button, we again use pagehide
event.Get notified & read regularly π