fix(analytics): prevent tracking on admin pages and local dev environments
Build and Push Docker Image / build (push) Successful in 19s
Build and Push Docker Image / build (push) Successful in 19s
This commit is contained in:
@@ -1,17 +1,40 @@
|
||||
module.exports = {
|
||||
injectHead({ pluginConfig }) {
|
||||
injectHead({ pluginConfig, pageType }) {
|
||||
const trackingId = pluginConfig.tracking_id;
|
||||
if (!trackingId) return '';
|
||||
|
||||
// 1. Never inject analytics on administrative moderation pages
|
||||
if (pageType === 'admin') {
|
||||
return '';
|
||||
}
|
||||
|
||||
// 2. Do not inject in development, staging, or testing modes (unless explicitly enabled)
|
||||
const isProd = process.env.NODE_ENV === 'production' && process.env.APP_ENV !== 'staging';
|
||||
if (!isProd && !pluginConfig.enable_in_dev) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return `
|
||||
<!-- Google Analytics (GA4 via Plugin) -->
|
||||
<script async src="https://www.googletagmanager.com/gtag/js?id=${trackingId}"></script>
|
||||
<script>
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
gtag('js', new Date());
|
||||
gtag('config', '${trackingId}');
|
||||
(function() {
|
||||
// 3. Client-side domain safeguard: only track on production pengzhan.dev domains
|
||||
var host = window.location.hostname;
|
||||
if (host !== 'pengzhan.dev' && !host.endsWith('.pengzhan.dev')) {
|
||||
window['ga-disable-${trackingId}'] = true;
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
window.gtag = function(){};
|
||||
return;
|
||||
}
|
||||
window.dataLayer = window.dataLayer || [];
|
||||
function gtag(){dataLayer.push(arguments);}
|
||||
window.gtag = gtag;
|
||||
gtag('js', new Date());
|
||||
gtag('config', '${trackingId}');
|
||||
})();
|
||||
</script>
|
||||
`;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user