From ad19da27d721117cf0603ad0a59378f17600b5d5 Mon Sep 17 00:00:00 2001 From: Tom Forbes Date: Wed, 13 Dec 2023 12:01:41 +0000 Subject: [PATCH] Check consents for gu.alreadyVisited (#26762) --- .../bootstraps/standard/alreadyVisited.ts | 24 +++++++++++++++++++ .../javascripts/bootstraps/standard/main.js | 9 ++----- 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 static/src/javascripts/bootstraps/standard/alreadyVisited.ts diff --git a/static/src/javascripts/bootstraps/standard/alreadyVisited.ts b/static/src/javascripts/bootstraps/standard/alreadyVisited.ts new file mode 100644 index 00000000000..1a5290b974d --- /dev/null +++ b/static/src/javascripts/bootstraps/standard/alreadyVisited.ts @@ -0,0 +1,24 @@ +import { onConsent } from '@guardian/consent-management-platform'; + +/** + * This local storage item is used to target ads if a user has the correct consents + */ +const AlreadyVisitedKey = 'gu.alreadyVisited'; + +const getAlreadyVisitedCount = (): number => { + const alreadyVisited = parseInt( + localStorage.getItem(AlreadyVisitedKey) ?? '', + 10, + ); + return !Number.isNaN(alreadyVisited) ? alreadyVisited : 0; +}; + +export const incrementAlreadyVisited = async (): Promise => { + const { canTarget } = await onConsent(); + if (canTarget) { + const alreadyVisited = getAlreadyVisitedCount() + 1; + localStorage.setItem(AlreadyVisitedKey, alreadyVisited.toString()); + } else { + localStorage.removeItem(AlreadyVisitedKey); + } +}; diff --git a/static/src/javascripts/bootstraps/standard/main.js b/static/src/javascripts/bootstraps/standard/main.js index 3c5b979a468..d67047be9b9 100644 --- a/static/src/javascripts/bootstraps/standard/main.js +++ b/static/src/javascripts/bootstraps/standard/main.js @@ -16,11 +16,8 @@ import fastdom from 'fastdom'; import raven from 'lib/raven'; import userPrefs from 'common/modules/user-prefs'; -import { storage } from '@guardian/libs'; -import { fetchJson } from 'lib/fetch-json'; import { mediator } from 'lib/mediator'; import { addEventListener } from 'lib/events'; -import { addCookie } from 'lib/cookies'; import { catchErrorsWithContext } from 'lib/robust'; import { markTime } from 'lib/user-timing'; import { isBreakpoint } from 'lib/detect'; @@ -35,6 +32,7 @@ import ophan from 'ophan/ng'; import { initAtoms } from './atoms'; import { initEmbedResize } from "./emailEmbeds"; import { setAdFreeCookie } from 'common/modules/commercial/user-features'; +import { incrementAlreadyVisited } from "bootstraps/standard/alreadyVisited"; const showHiringMessage = () => { try { @@ -159,11 +157,8 @@ const bootStandard = () => { setAdFreeCookie(1); } - // set local storage: gu.alreadyVisited if (window.guardian.isEnhanced) { - const key = 'gu.alreadyVisited'; - const alreadyVisited = parseInt(storage.local.getRaw(key), 10) || 0; - storage.local.setRaw(key, alreadyVisited + 1); + void incrementAlreadyVisited(); } ophan.setEventEmitter(mediator);