'Unload/remove/disable Google Analytics dynamically without a full page load
I see various guides on how to add Google Analytics/ GA into a page dynamically, e.g. for a Single Page Application/ SPA.
How can I do the reverse, i.e. a user clicks a button and Google Analytics is completely removed from that page, without a full page load?
The instructions at https://developers.google.com/analytics/devguides/collection/gtagjs/user-opt-out suggesting to set
window['ga-disable-GA_MEASUREMENT_ID'] = true;
I don't think helps doing this, since the page states
This window property must be set before any calls to gtag() are made
Solution 1:[1]
You can do it easily by refreshing the page on opt-out and setting:
window['ga-disable-TRACKING-ID'] = true;
before gtag is loaded.
More detail here: User opt-out with gtag.js
to disable tracking (not all) without reload:
gtag('config', 'GA_MEASUREMENT_ID', { 'send_page_view': false })
gtag('set', 'allow_ad_personalization_signals', false)
Solution 2:[2]
I ended up solving this problem a bit differently than I have seen posted anywhere. The app I'm working on tracks globally but also needs to track content that's own by an org for that org.
so i don't do this
gtag('config', 'GA_MEASUREMENT_ID)
and instead use the send_to
field. which basically looks something like
const measurementIds = [ GA_MEASUREMENT_ID_1, GA_MEASUREMENT_ID_2 ];
measurementIds.forEach(id => {
gtag('event', 'page_view', { send_to: id });
})
as users go in out of various content I add or remove their ID to the measurementIds
array.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | denov |