Behavioral Analysis: The Challenge of the Tab
Currently working on a Saas that reads a user’s behavior on a site. The goal is keeping it lightweight and privacy centered. All interactions are recorded in the browser. When the browser hides the page, a compact summary is calculated and sent to a cloudflare worker for insertion into a D1 DB. The exit events are strictly bound using this function. // Bind exit triggers strictly once if ( this .…
Developing a software as a service (SaaS) application that monitors user behavior on websites while emphasizing privacy remains a key objective. All user interactions are captured within the browser itself. Upon exiting the webpage, a concise summary is generated and transmitted to a Cloudflare worker for storage in a D1 database. The termination of events is strictly managed using a specific function.
Upon initiating the process, two attempts are made to send the data. The first attempt employs the `navigator.sendBeacon()` method, while the second fallback utilizes the `fetch()` function if the initial attempt fails.
However, a challenge arises when users return to the tab. The function records their return but does not fire the event again due to a locking mechanism implemented in the `handleExit` function. This locking mechanism prevents further beacon firing during the session. To resolve this, the `_hasSent` variable must be reset to `false` when users return to the tab, allowing the beacon to fire again.
To address this issue, a new `handleVisibilityChange` function is introduced. This function triggers when the user hides the tab, navigates away, or closes the browser. It checks if the data has already been sent; if so, it returns to prevent duplicate immediate fires. If not, it sets the `_hasSent` variable to `true` to lock the beacon and triggers the `forceSend()` function.
When the user returns to the tab, indicated by a change in the `document.visibilityState` to `visible`, the `_hasSent` variable is set back to `false`, unlocking the beacon and allowing it to fire again.
Despite this resolution, a new problem emerges: multiple writes for the same session ID, which acts as the primary key. To handle duplicate session IDs, the `write` or `replace` method is employed. This approach ensures that the latest data overwrites the old data, effectively managing the scenario of users returning to the same tab within the same session. This process ensures the most recent data is stored in the D1 database, maintaining the integrity and accuracy of the user behavior data being collected.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.