hugo-theme-stack/layouts/partials/head/analytics/provider/umami.html
Chen Lily 96be9b767b
**feat:** Add Umami analytics and view count to article details
- Added conditional rendering for view count in article details based on `Site.Params.Analytics`.
- Updated Umami analytics script to use structured parameters and fixed script inclusion.
- Included Umami analytics script in the head section.
2025-02-28 10:55:11 +08:00

37 lines
1.7 KiB
HTML

{{- $umami := .Site.Params.Analytics.Umami -}}
{{- if $umami -}}
{{- $host := default "https://cloud.umami.is" $umami.Host -}}
{{- if and (not $umami.Disabled) ($umami.SiteId) -}}
<script defer src="{{ $host }}/script.js" data-website-id="{{ $umami.SiteId }}"></script>
{{- if not .IsHome -}}
<script>
window.addEventListener("DOMContentLoaded", () => {
const wrapper = document.getElementsByClassName("article-time--count-wrapper")[0];
const e = wrapper && wrapper.getElementsByClassName("article-time--count")[0];
if (e == null)
return;
const path = window.location.pathname;
let options;
{{- if $umami.Token -}}
const token = {{ $umami.Token }};
options = {
headers: {
'Authorization': `Bearer ${token}`
}
};
{{- end -}}
let st = new Date({{ $umami.StartAt }}).getTime();
if (isNaN(st))
st = 0; // fallback to 1970-01-01T00:00:00Z
const now = new Date().getTime();
const url = `{{ $host }}/api/websites/{{ $umami.SiteId }}/stats?startAt=${st}&endAt=${now}&url=${encodeURIComponent(path)}`;
fetch(url, options).then(r => r.json()).then(data => {
wrapper.style.display = '';
e.textContent = String(data.visits ? data.visits.value : 0);
});
});
</script>
{{- end -}}
{{- end -}}
{{- end -}}