hugo-toha / toha

A Hugo theme for personal portfolio
https://hugo-toha.github.io
MIT License
1.06k stars 612 forks source link

A better approach to analytics #1006

Open davidgs opened 1 month ago

davidgs commented 1 month ago

Question

I submitted -- and you merged, thank you!! -- a PR for enabling stat counter analytics/page counter. But I am still seeing problems in having the script executed because it is not hashed, etc. So I think I've come up with a better way to include analytics that doesn't involve adding in-line scripts, etc.

in /assets/scripts/features analytics ├── index.js ├── posthog.js └── statcounter.js

in `features/index.js

if (process.env.FEATURE_ANALYTICS === '1') {
  import('./analytics')
}

in features/analytics/index.js

import * as params from '@params';

if (params.analytics) { // probably don't need this one
  if (params.analytics.statcounter) {
    import('./statcounter');
  }
  if (params.analytics.posthog) {
    import('./posthog');
  }
  if (params.analytics.matomo) {
    import('./matomo')l
  }
}

assets/scripts/features/statcounter.js

import * as params from '@params';

    console.log('StatCounter: Statcounter enabled');
    const sc_project = params.analytics.statcounter.project;
    const sc_invisible = params.analytics.statcounter.invisible;
    const sc_security = params.analytics.statcounter.security;
    const scJsHost =  "https://www.statcounter.com/js/";

    const ns = document.createElement('noscript');
    ns.setAttribute('class', 'statcounter');
    const a = document.createElement('a');
    a.setAttribute('title', 'web counter');
    a.setAttribute('href', 'https://statcounter.com/');
    a.setAttribute('target', '_blank');
    const img = document.createElement('img');
    img.setAttribute('class', 'statcounter');
    img.setAttribute('src', 'https://c.statcounter.com/' + params.analytics.statcounter.project + '/0/' + params.analytics.statcounter.security + '/' + params.analytics.statcounter.invisible + '/');
    img.setAttribute('alt', 'web counter');
    img.setAttribute('referrerPolicy', 'no-referrer-when-downgrade');
    ns.appendChild(a);
    a.appendChild(img);
document.body.appendChild(ns);

Now all script elements are included in application.js and are hashed, so no in-line scripts.

What do you think?

hossainemruz commented 1 week ago

@davidgs feel free to send a PR.