From eb937737c203666f534071e6be4b153112c23986 Mon Sep 17 00:00:00 2001 From: xiaojunnuo Date: Sun, 20 Oct 2024 03:35:08 +0800 Subject: [PATCH] chore: baidutongji --- docs/.vitepress/theme/index.ts | 17 +++++++ docs/.vitepress/theme/plugins/baidutongji.ts | 49 ++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 docs/.vitepress/theme/plugins/baidutongji.ts diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts index b0a7a9cce..94abedae8 100644 --- a/docs/.vitepress/theme/index.ts +++ b/docs/.vitepress/theme/index.ts @@ -4,6 +4,11 @@ import type { Theme } from 'vitepress' import DefaultTheme from 'vitepress/theme' import './style.css' import Layout from './Layout.vue' + +import { registerAnalytics, siteIds, trackPageview } from './plugins/baidutongji' +import { inBrowser } from "vitepress"; + + export default { extends: DefaultTheme, Layout, @@ -14,5 +19,17 @@ export default { // }, enhanceApp({ app, router, siteData }) { // ... + if (inBrowser) { + registerAnalytics(siteIds) + + window.addEventListener('hashchange', () => { + const { href: url } = window.location + trackPageview(siteIds, url) + }) + + router.onAfterRouteChanged = (to) => { + trackPageview(siteIds, to) + } + } } } satisfies Theme diff --git a/docs/.vitepress/theme/plugins/baidutongji.ts b/docs/.vitepress/theme/plugins/baidutongji.ts new file mode 100644 index 000000000..5363141c5 --- /dev/null +++ b/docs/.vitepress/theme/plugins/baidutongji.ts @@ -0,0 +1,49 @@ +import { inBrowser } from 'vitepress' + +/** + * 统计站点的 ID 列表 + */ +export const siteIds = 'a6ce877a899ae44292e4f854a53d688e' + +declare global { + interface Window { + _hmt: any + } +} + +/** + * 注册统计 + */ +export function registerAnalytics(siteId: string) { + if (!inBrowser) + return + if (document.querySelector(`#analytics-plugin-${siteId}`)) + return + window._hmt = window._hmt ? window._hmt : [] + const script = document.createElement('script') + script.id = `analytics-${siteId}` + script.async = true + script.src = `https://hm.baidu.com/hm.js?${siteId}` + document.querySelector('head')?.appendChild(script) +} + +/** + * 上报 PV 数据 + * @param siteId - 站点 ID + * @param pageUrl - 页面 URL + */ +export function trackPageview(siteId: string, pageUrl: string) { + if (!inBrowser) + return + if (!pageUrl || typeof pageUrl !== 'string') + pageUrl = '/' + + if (pageUrl.startsWith('http')) { + const urlFragment = pageUrl.split('/') + const origin = `${urlFragment[0]}//${urlFragment[2]}` + pageUrl = pageUrl.replace(origin, '') + } + + window._hmt.push(['_setAccount', siteId]) + window._hmt.push(['_trackPageview', pageUrl]) +}