Irritating Popup - (or perhaps a more elegant alternative)

My current challenge involves tracking the time a user spends with a specific window in focus. I aim to record this duration accurately and pause the timer when the user switches to another window, then resume it upon returning. Ultimately, I want to measure how long it takes for a user to read the content displayed on the page.

This is part of a review process where trusted members need to log their reading time. By maintaining a running total, discrepancies between user-reported times and actual window activity can be identified for further investigation.

My approach entails utilizing JavaScript to create a timer that runs when the window is in focus, pauses during blur or closure events, and sends data back to the server via Ajax calls. Any subsequent return visits by the user would add to the existing time record.

I've encountered issues with onUnload not working as expected, especially when the browser is closed. As a workaround, I'm considering launching a new window upon document closure to trigger the logging process before self-closing.

If anyone has a more efficient solution for this scenario, particularly addressing concerns about design flaws, I'm eager to hear suggestions. (Please note that compatibility with IE7 is necessary due to our intranet environment.)

Below is a snippet of code I've been testing, but encountering some challenges:

<script type="text/javascript">

var closeMe = 0;
var logMe = 0;

function onBlur() {
    closeMe = setInterval('window.close()',120000);
};

function onFocus(){
    clearInterval(closeMe);  
    logMe = setInterval('logTime()',60000);
};

function logTime() {
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "ajax-on-time-interval.php", false);
    xhReq.send(null);
    var serverResponse = xhReq.responseText;
    alert(serverResponse); 
}

if (/*@cc_on!@*/false) {
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

</script>

Answer №1

In my opinion, implementing a regular Ajax-based "heartbeat" to update the database data at set intervals could be a more elegant solution compared to using pop-ups. This approach also bypasses potential issues with browser handling of events like onunload.

Of course, this method assumes that JavaScript will be enabled on the devices in question, which seems reasonable given the context of your query.

Answer №2

The MDC documentation mentions window.onfocus and onblur, although they are not considered standard practices. Interestingly, Internet Explorer has document.onfocusin and .onfocusout available:

if (/*@cc_on!@*/false) { // check for Internet Explorer
    document.onfocusin = onFocus;
    document.onfocusout = onBlur;
} else {
    window.onfocus = onFocus;
    window.onblur = onBlur;
}

I have yet to test this myself; I came across it in an article here:

Answer №3

An unconventional but effective method to mitigate the problem of browsers closing or crashing is to implement an ajax function that continuously communicates with the server database while the document remains in focus. By doing so, in case of a client crash, you can ensure that the accuracy of how long the document was open is maintained within a 30-second margin.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combine several JSON files into a single file

After spending countless hours searching on Google, I finally gathered the courage to ask my question here. I have several json files. localhost/feed01.json localhost/feed02.json localhost/feed03.json All of the json file structures are similar to this ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

Javascript encountering compatibility issues with certain versions of Internet Explorer; employing browser detection workaround

Unfortunately, Internet Explorer is causing issues when trying to execute this script (specifically the 'else' part). Despite numerous attempts, I have been unable to resolve it. $(document).ready(function(){ if (navigator.appName != "Micros ...

The Karma Node Package is failing to run and providing no information

I've been troubleshooting an issue with my karma.conf.js file for the past two days. Despite my efforts, the terminal output provides no helpful information to identify the source of the problem. There are no hints within the document itself indicatin ...

Generating an interactive Datepicker using Jquery

How can I design a dynamic date picker similar to the image provided below? https://i.sstatic.net/euoNI.png I have attempted to create one, but I am looking for a more interactive date picker. Is there a way to achieve the design shown in the image? The ...

Converting Epoch time to date in NextJS

In my NextJS app, I have a date displayed in a div. <div>{post.createdat}</div> The date is shown in epoch time (1609553315666), indicating the number of seconds that have elapsed since 1970. I'm wondering if there's a way to conver ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Error message "Error: listen EADDRINUSE" is reported by node.js when calling child_process.fork

Whenever the 'child_process.fork('./driver')' command is executed, an error occurs: Error: listen EADDRINUSE at exports._errnoException (util.js:746:11) at Agent.Server._listen2 (net.js:1156:14) at listen (net.js:1182:10) ...

Using Plotly.js within a deleted Vue.js component may result in displaying an incorrect chart

Issue I am facing a problem with deleting one of the components that contains a chart. Even after deleting the component, the chart remains visible. To see an example, check out this jsfiddle: https://jsfiddle.net/m4ywp5fc/4/ Solution Attempted I attem ...

How to retrieve user data based on ID using Angular SDK

I have limited experience with the Angular SDK and lb-service, and I'm unsure about how to retrieve another user's information by their ID within a controller. I am trying to implement a feature for displaying a friend list, where each user only ...

Restrict user uploads to a maximum of 5 posts per minute using Jquery

Recently, I have implemented this jQuery/AJAX code snippet: var uploaded=0; if (uploaded!=0) { setInterval(function() { uploaded--; }, 60000); alert(uploaded); } $(".UploadMSub").click(function(event){ event.preventDefault(); ...

Incorporating JavaScript and CSS files into a content page of a master page in ASP.NET: Steps to follow

I am facing an issue with adding javascript files and css to a content page of a master page in asp.net. I attempted to include a datetime picker on my ContentPage, but it only works on the masterpage. When I try to add the same code to my contentpage, i ...

The jQuery function is running double even after I cleared the DOM with the empty() method

Twice, or multiple times if going back and forth, the Jquery function is triggered. Upon loading LoginMenu.jsp, WorkOrder.jsp is loaded within a specified ID. Once WorkOrder.jsp loads, it then loads schedule.jsp in the schedule tab defined in WorkOrders.j ...

I am interested in developing a JavaScript program that can calculate multiples of 0.10

I am looking to let users input values that are multiples of 0.10, such as - 0.10, 0.20, 0.30....1.00, 1.10, 1.20...1.90, and so on. When a user enters a value in the text box, I have been checking the following validation: amount % 0.10 == 0 Is this a ...

PHP query for beginners. Integrating JavaScript into a PHP webpage

Hey there! I am not familiar with PHP development, as I have never worked with it before. However, I have been tasked with adding a Google Shopping cart tracking code to a website. After someone completes an order, they are sent to finishorder.php. Upon re ...

Issue encountered during upgrade from version 10 to version 13 in a Next.js migration: Module not found

I've been working on upgrading our old site from version 10 to version 13, and we have a custom backend built with express. However, I keep encountering a "Module not found" error when running the project concurrently, specifically when running the cl ...

Incorporate a SharpSpring form within a custom React component

Trying to integrate a Sharpspring form script into my React component (page.jsx). The form needs to be placed outside the <head></head> element and inside the <div> where I want to display it. The original HTML code for embedding the for ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

What could be the reason for my code generating the error [$http:badreq]?

I'm currently attempting to retrieve JSON data from a certain URL and am having trouble getting it to work. Despite going through the Angular documentation and other resources, I still can't pinpoint the issue due to my limited experience with An ...

Tips on how to showcase the current time in the local timezone on Next.js without encountering the error message "Text content does not match server-rendered HTML."

Currently, I am sharpening my Next.js skills by building a blog. My current challenge involves formatting a static ISO time string (which represents the creation time of blog posts) to match the local timezone of the user. <div className='post-time ...