This code is a JavaScript snippet for a lightweight analytics...
May 18, 2025 at 11:59 AM
This code is a JavaScript snippet for a lightweight analytics tracking system. Here's a breakdown of what it does:
-
Setup the Tracking Endpoint:
- The
data-api
attribute is used to specify the URL where the analytics data will be sent. If not provided, it defaults to"https://lb1.beamanalytics.io/api/log"
.
- The
-
Defines
window.beam
Function:- The
beam
function is responsible for collecting and sending analytics data. It checks several conditions to ensure tracking is appropriate:- Doesn't track if the hostname is
localhost
,127.0.0.1
, orfile:
(to avoid local development tracking). - Avoids tracking in testing environments like NightmareJS, Cypress, or if run with WebDriver.
- Doesn't track if the hostname is
- If tracking is allowed:
- It collects data such as:
width
: The browser's viewport width.hostname
: The website's hostname.pathname
: The current path (or a custom path passed as an argument).referrer
: The referrer URL, if applicable and external.user_agent
: The browser's user agent.locale
: The browser's language or locale settings.params
: Any query parameters from the URL.token
: A token from thedata-token
attribute or globalwindow.beam_token
.title
: The current page's title.hash
: Any URL hash values (e.g.,#section1
).
- Sends this data as a JSON payload to the tracking API endpoint using an HTTP POST request.
- It collects data such as:
- The
-
Track on Navigation:
- It hooks into the
window.history.pushState
andpopstate
events to ensure tracking happens when users navigate between pages without fully reloading (for single-page applications). - When
pushState
is called (e.g., navigating to a new route), it triggers thebeam
function to log the navigation data.
- It hooks into the
-
Initial Execution:
- At the end of the script, the
beam
function is invoked to track the initial page load.
- At the end of the script, the
Summary:
This code tracks user interactions and sends analytics data to a remote server. It gathers details about the user's browser, page navigation, URL parameters, and referrer, then logs this data via POST requests. It integrates well into modern single-page applications by watching for navigation changes.
Generate your own explanations
Download our vscode extension
Read other generated explanations
Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node