7

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

3
  • You want completely remove? whether disabling it wil do? Commented Jan 27, 2020 at 14:47
  • @PramodNikam Disabling will do, but ideally, completely remove. Commented Jan 27, 2020 at 14:48
  • You can disable it at the very least and remove upon next refresh. You could try removing the script tag from head but I am not sure if that works. You can also remove the cookies set by google in js Commented Jan 27, 2020 at 14:58

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Understood, but the question is how to do this without refreshing the page.
gtag('config', 'GA_MEASUREMENT_ID', { 'send_page_view': false }) and gtag('set', 'allow_ad_personalization_signals', false)
or don't use default gtag, but some library -- for example in my react project I use github.com/react-ga/react-ga and with it you have full control over logged data and can disable it easily
that react lib is just a wrapper for gtag. it also looks like a lot of code to basically do the same think i have suggested in my answer.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.