简体   繁体   中英

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, eg for a Single Page Application/ SPA.

How can I do the reverse, ie 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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM