Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: track time spent on a page #1876

Merged
merged 27 commits into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
db562b0
feat: track time spent on a page
MoumitaM Oct 8, 2024
9c4a494
chore: moved the comment to appt place
MoumitaM Oct 8, 2024
02ffa04
refactor: trackPageLifecycleEvents fn
MoumitaM Oct 9, 2024
5813d01
chore: review comment addressed
MoumitaM Oct 9, 2024
f864f6a
chore: review comment addressed
MoumitaM Oct 9, 2024
eafe04f
chore: review comment addressed
MoumitaM Oct 9, 2024
5615d68
refactor: trackPageLifecycleEvents fn will be called from load api
MoumitaM Oct 14, 2024
e7e41aa
Merge branch 'develop' into feat/SDK-2478-track-timespent-on-a-page
MoumitaM Oct 14, 2024
72555d5
chore: addressed review comment
MoumitaM Oct 14, 2024
a390642
feat: modified load options structure
MoumitaM Oct 14, 2024
40c683c
chore: trackPageLifecycleEvents fn has been refactored and unit tests…
MoumitaM Oct 16, 2024
cc62338
chore: size limit updated
MoumitaM Oct 16, 2024
ab72611
Merge branch 'develop' into feat/SDK-2478-track-timespent-on-a-page
MoumitaM Oct 16, 2024
e4d5492
chore: typo corrected
MoumitaM Oct 16, 2024
6c7e207
chore: unit tests
MoumitaM Oct 17, 2024
8da4e56
Merge branch 'develop' into feat/SDK-2478-track-timespent-on-a-page
MoumitaM Oct 17, 2024
26a26c5
chore: size limit update
MoumitaM Oct 18, 2024
6455d95
chore: addressed review comments
MoumitaM Oct 18, 2024
56b1859
chore: eslint issue fixed
MoumitaM Oct 18, 2024
92b7442
fix: execution of cb when multiplt event listeners are attached
MoumitaM Oct 21, 2024
82fb915
chore: inline doc updated
MoumitaM Oct 21, 2024
6c9a94d
chore: readme updated
MoumitaM Oct 21, 2024
412beeb
Merge branch 'develop' into feat/SDK-2478-track-timespent-on-a-page
MoumitaM Oct 21, 2024
7c97388
chore: unit test added
MoumitaM Oct 22, 2024
90c97ec
Merge branch 'develop' into feat/SDK-2478-track-timespent-on-a-page
MoumitaM Oct 22, 2024
ebcc0c3
chore: unit test updated
MoumitaM Oct 22, 2024
7aea66e
Merge branch 'feat/SDK-2478-track-timespent-on-a-page' of https://git…
MoumitaM Oct 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/analytics-js-common/src/types/IRudderAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ export interface IRudderAnalytics<T = any> {
analyticsInstances: Record<string, T>;
defaultAnalyticsKey: string;
logger: ILogger;
visitId: string;
pageLoadedTimestamp: number;
saikumarrs marked this conversation as resolved.
Show resolved Hide resolved

/**
* Set the writeKey of the analytics instance that should be default
Expand Down
12 changes: 12 additions & 0 deletions packages/analytics-js-common/src/types/LoadOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,17 @@
events?: PreConsentEventsOptions;
};

export enum PageLifecycleEvents {
LOADED = 'Page Loaded',
UNLOADED = 'Page Unloaded',

Check warning on line 113 in packages/analytics-js-common/src/types/LoadOptions.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js-common/src/types/LoadOptions.ts#L112-L113

Added lines #L112 - L113 were not covered by tests
}

export type TrackPageLifecycleOptions = {
enabled: boolean; // default false
events?: PageLifecycleEvents[];
options?: ApiOptions;
};

/**
* Represents the options parameter in the load API
*/
Expand Down Expand Up @@ -150,6 +161,7 @@
externalAnonymousIdCookieName?: string;
useServerSideCookies?: boolean;
dataServiceEndpoint?: string;
trackPageLifecycle?: TrackPageLifecycleOptions;
};

export type ConsentOptions = {
Expand Down
6 changes: 3 additions & 3 deletions packages/analytics-js/.size-limit.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export default [
name: 'Core - Modern - NPM (CJS)',
path: 'dist/npm/modern/cjs/index.cjs',
import: '*',
limit: '24.5 KiB',
limit: '25 KiB',
},
{
name: 'Core - Modern - NPM (UMD)',
Expand All @@ -47,7 +47,7 @@ export default [
{
name: 'Core - Modern - CDN',
path: 'dist/cdn/modern/iife/rsa.min.js',
limit: '24.5 KiB',
limit: '25 KiB',
},
{
name: 'Core (Bundled) - Legacy - NPM (ESM)',
Expand Down Expand Up @@ -113,7 +113,7 @@ export default [
name: 'Core (Content Script) - Modern - NPM (CJS)',
path: 'dist/npm/modern/content-script/cjs/index.cjs',
import: '*',
limit: '38.5 KiB',
limit: '39 KiB',
},
{
name: 'Core (Content Script) - Modern - NPM (UMD)',
Expand Down
5 changes: 4 additions & 1 deletion packages/analytics-js/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -150,12 +150,15 @@
// events: {
// delivery: 'buffer'
// }
}
},
// plugins: [
// 'StorageEncryption',
// 'StorageMigrator',
// 'XhrQueue'
// ]
// trackPageLifecycle:{
// enabled: true,
// }
};

rudderanalytics.load('__WRITE_KEY__', '__DATAPLANE_URL__', loadOptions);
Expand Down
88 changes: 82 additions & 6 deletions packages/analytics-js/src/app/RudderAnalytics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,19 @@
} from '@rudderstack/analytics-js-common/utilities/eventMethodOverloads';
import type { IRudderAnalytics } from '@rudderstack/analytics-js-common/types/IRudderAnalytics';
import type { Nullable } from '@rudderstack/analytics-js-common/types/Nullable';
import type {
AnonymousIdOptions,
ConsentOptions,
LoadOptions,
import {
PageLifecycleEvents,
type AnonymousIdOptions,
type ConsentOptions,
type LoadOptions,
} from '@rudderstack/analytics-js-common/types/LoadOptions';
import type { ApiCallback, ApiOptions } from '@rudderstack/analytics-js-common/types/EventApi';
import type { ApiObject } from '@rudderstack/analytics-js-common/types/ApiObject';
import { RS_APP } from '@rudderstack/analytics-js-common/constants/loggerContexts';
import { isString } from '@rudderstack/analytics-js-common/utilities/checks';
import type { IdentifyTraits } from '@rudderstack/analytics-js-common/types/traits';
import { generateUUID } from '@rudderstack/analytics-js-common/utilities/uuId';
import { onPageLeave } from '@rudderstack/analytics-js-common/utilities/page';
import { GLOBAL_PRELOAD_BUFFER } from '../constants/app';
import {
getPreloadedLoadEvent,
Expand All @@ -29,8 +32,13 @@
import type { IAnalytics } from '../components/core/IAnalytics';
import { Analytics } from '../components/core/Analytics';
import { defaultLogger } from '../services/Logger/Logger';
import { EMPTY_GROUP_CALL_ERROR, WRITE_KEY_NOT_A_STRING_ERROR } from '../constants/logMessages';
import {
EMPTY_GROUP_CALL_ERROR,
PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING,
WRITE_KEY_NOT_A_STRING_ERROR,
} from '../constants/logMessages';
import { defaultErrorHandler } from '../services/ErrorHandler';
import { state } from '../state';

// TODO: add analytics restart/reset mechanism

Expand All @@ -45,6 +53,8 @@
analyticsInstances: Record<string, IAnalytics> = {};
defaultAnalyticsKey = '';
logger = defaultLogger;
visitId = generateUUID();
pageLoadedTimestamp = Date.now();

// Singleton with constructor bind methods
constructor() {
Expand Down Expand Up @@ -80,7 +90,7 @@
this.consent = this.consent.bind(this);

RudderAnalytics.globalSingleton = this;

this.logger?.setMinLogLevel('WARN');
MoumitaM marked this conversation as resolved.
Show resolved Hide resolved
saikumarrs marked this conversation as resolved.
Show resolved Hide resolved
// start loading if a load event was buffered or wait for explicit load call
this.triggerBufferedLoadEvent();

Expand Down Expand Up @@ -133,6 +143,70 @@
this.getAnalyticsInstance(writeKey).load(writeKey, dataPlaneUrl, loadOptions);
}

/**
* A function to track page lifecycle events like page loaded and page unloaded
* @param preloadedEventsArray
* @param loadOptions
* @returns
*/
// eslint-disable-next-line class-methods-use-this
trackPageLifecycleEvents(
preloadedEventsArray: PreloadedEventCall[],
loadOptions?: Partial<LoadOptions>,
) {
const { trackPageLifecycle, useBeacon } = loadOptions ?? {};
const {
events = [PageLifecycleEvents.LOADED, PageLifecycleEvents.UNLOADED],
enabled = false,
options = {},
} = trackPageLifecycle ?? {};

if (!enabled) {
return;
}

// track page loaded event
if (events.length === 0 || events.includes(PageLifecycleEvents.LOADED)) {
preloadedEventsArray.unshift([

Check warning on line 170 in packages/analytics-js/src/app/RudderAnalytics.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/app/RudderAnalytics.ts#L170

Added line #L170 was not covered by tests
'track',
PageLifecycleEvents.LOADED,
{ visitId: this.visitId },
{
...options,
originalTimestamp: new Date(this.pageLoadedTimestamp).toISOString(),
},
]);
}

// track page unloaded event
if (events.length === 0 || events.includes(PageLifecycleEvents.UNLOADED)) {
if (useBeacon === true) {
// Register the page unloaded lifecycle event listeners
onPageLeave((isAccessible: boolean) => {

Check warning on line 185 in packages/analytics-js/src/app/RudderAnalytics.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/app/RudderAnalytics.ts#L185

Added line #L185 was not covered by tests
if (isAccessible === false && state.lifecycle.loaded.value) {
const pageUnloadedTimestamp = Date.now();
const visitDuration = pageUnloadedTimestamp - this.pageLoadedTimestamp;
this.track(

Check warning on line 189 in packages/analytics-js/src/app/RudderAnalytics.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/app/RudderAnalytics.ts#L187-L189

Added lines #L187 - L189 were not covered by tests
PageLifecycleEvents.UNLOADED,
{
visitId: this.visitId,
visitDuration,
},
{
...options,
originalTimestamp: new Date(pageUnloadedTimestamp).toISOString(),
},
);
}
});
} else {
// throw warning if beacon is disabled
this.logger.warn(PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING(RS_APP));

Check warning on line 204 in packages/analytics-js/src/app/RudderAnalytics.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/app/RudderAnalytics.ts#L204

Added line #L204 was not covered by tests
}
}
setExposedGlobal(GLOBAL_PRELOAD_BUFFER, clone(preloadedEventsArray));

Check warning on line 207 in packages/analytics-js/src/app/RudderAnalytics.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/app/RudderAnalytics.ts#L207

Added line #L207 was not covered by tests
}

/**
* Trigger load event in buffer queue if exists and stores the
* remaining preloaded events array in global object
Expand All @@ -155,6 +229,8 @@

// Process load method if present in the buffered requests
if (loadEvent.length > 0) {
// Track page loaded lifecycle event if enabled
this.trackPageLifecycleEvents(preloadedEventsArray, loadEvent[3]);
saikumarrs marked this conversation as resolved.
Show resolved Hide resolved
saikumarrs marked this conversation as resolved.
Show resolved Hide resolved
MoumitaM marked this conversation as resolved.
Show resolved Hide resolved
// Remove the event name from the Buffered Event array and keep only arguments
loadEvent.shift();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
Expand Down
8 changes: 8 additions & 0 deletions packages/analytics-js/src/components/utilities/loadOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,14 @@
normalizedLoadOpts.preConsent = removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);
}

if (!isObjectLiteralAndNotNull(normalizedLoadOpts.trackPageLifecycle)) {
delete normalizedLoadOpts.trackPageLifecycle;
} else {
normalizedLoadOpts.trackPageLifecycle = removeUndefinedAndNullValues(

Check warning on line 127 in packages/analytics-js/src/components/utilities/loadOptions.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/components/utilities/loadOptions.ts#L127

Added line #L127 was not covered by tests
normalizedLoadOpts.trackPageLifecycle,
);
}

const mergedLoadOptions: LoadOptions = mergeDeepRight(loadOptionsFromState, normalizedLoadOpts);

return mergedLoadOptions;
Expand Down
4 changes: 4 additions & 0 deletions packages/analytics-js/src/constants/logMessages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,9 @@
const BAD_COOKIES_WARNING = (key: string) =>
`The cookie data for ${key} seems to be encrypted using SDK versions < v3. The data is dropped. This can potentially stem from using SDK versions < v3 on other sites or web pages that can share cookies with this webpage. We recommend using the same SDK (v3) version everywhere or avoid disabling the storage data migration.`;

const PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING = (context: string) =>
`${context}${LOG_CONTEXT_SEPARATOR}Page Unloaded event can only be tracked when the Beacon transport is active. Please enable "useBeacon" load API option.`;

Check warning on line 261 in packages/analytics-js/src/constants/logMessages.ts

View check run for this annotation

Codecov / codecov/patch

packages/analytics-js/src/constants/logMessages.ts#L261

Added line #L261 was not covered by tests

export {
UNSUPPORTED_CONSENT_MANAGER_ERROR,
UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING,
Expand Down Expand Up @@ -321,4 +324,5 @@
COMPONENT_BASE_URL_ERROR,
SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING,
BAD_COOKIES_WARNING,
PAGE_UNLOAD_ON_BEACON_DISABLED_WARNING,
};
9 changes: 8 additions & 1 deletion packages/analytics-js/src/state/slices/loadOptions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { signal } from '@preact/signals-core';
import { clone } from 'ramda';
import type { LoadOptions } from '@rudderstack/analytics-js-common/types/LoadOptions';
import {
PageLifecycleEvents,
type LoadOptions,
} from '@rudderstack/analytics-js-common/types/LoadOptions';
import type { LoadOptionsState } from '@rudderstack/analytics-js-common/types/ApplicationState';
import {
DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,
Expand Down Expand Up @@ -39,6 +42,10 @@ const defaultLoadOptions: LoadOptions = {
},
sendAdblockPageOptions: {},
useServerSideCookies: false,
trackPageLifecycle: {
enabled: false,
events: [PageLifecycleEvents.LOADED, PageLifecycleEvents.UNLOADED],
},
};

const loadOptionsState: LoadOptionsState = signal(clone(defaultLoadOptions));
Expand Down