Skip to content

Commit

Permalink
Merge 1cf0a53 into 479b32f
Browse files Browse the repository at this point in the history
  • Loading branch information
emma-imber authored Jul 9, 2024
2 parents 479b32f + 1cf0a53 commit 69d4f2f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/brave-peaches-confess.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@guardian/commercial': minor
---

Refactor metrics bypassing
17 changes: 12 additions & 5 deletions src/core/send-commercial-metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,12 +187,17 @@ function gatherMetricsOnPageUnload(): void {
const listener = (e: Event): void => {
switch (e.type) {
case 'visibilitychange':
if (document.visibilityState === 'hidden') {
if (
document.visibilityState === 'hidden' &&
window.guardian.config.shouldSendCommercialMetrics === true
) {
gatherMetricsOnPageUnload();
}
return;
case 'pagehide':
gatherMetricsOnPageUnload();
if (window.guardian.config.shouldSendCommercialMetrics === true) {
gatherMetricsOnPageUnload();
}
return;
}
};
Expand Down Expand Up @@ -232,7 +237,7 @@ async function bypassCommercialMetricsSampling(): Promise<void> {
const consented = await checkConsent();

if (consented) {
addVisibilityListeners();
window.guardian.config.shouldSendCommercialMetrics = true;
} else {
log('commercial', "Metrics won't be sent because consent wasn't given");
}
Expand Down Expand Up @@ -267,6 +272,7 @@ async function initCommercialMetrics({
setEndpoint(isDev);
setDevProperties(isDev);
setAdBlockerProperties(adBlockerInUse);
addVisibilityListeners();

if (window.guardian.config.commercialMetricsInitialised) {
return false;
Expand All @@ -276,10 +282,10 @@ async function initCommercialMetrics({

const userIsInSamplingGroup = Math.random() <= sampling;

if (isDev || userIsInSamplingGroup) {
if (userIsInSamplingGroup) {
const consented = await checkConsent();
if (consented) {
addVisibilityListeners();
window.guardian.config.shouldSendCommercialMetrics = true;
return true;
}
log('commercial', "Metrics won't be sent because consent wasn't given");
Expand All @@ -296,6 +302,7 @@ export const _ = {
transformToObjectEntries,
reset: (): void => {
window.guardian.config.commercialMetricsInitialised = false;
window.guardian.config.shouldSendCommercialMetrics = false;
commercialMetricsPayload = {
page_view_id: undefined,
browser_id: undefined,
Expand Down
1 change: 1 addition & 0 deletions src/types/global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ interface Config {
pageViewId: string;
};
page: PageConfig;
shouldSendCommercialMetrics?: boolean;
stage: Stage;
switches: Record<string, boolean | undefined>;
tests?: {
Expand Down

0 comments on commit 69d4f2f

Please sign in to comment.