chore: baidutongji

pull/229/head
xiaojunnuo 2024-10-20 03:35:08 +08:00
parent e646f01c2a
commit eb937737c2
2 changed files with 66 additions and 0 deletions

View File

@ -4,6 +4,11 @@ import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme' import DefaultTheme from 'vitepress/theme'
import './style.css' import './style.css'
import Layout from './Layout.vue' import Layout from './Layout.vue'
import { registerAnalytics, siteIds, trackPageview } from './plugins/baidutongji'
import { inBrowser } from "vitepress";
export default { export default {
extends: DefaultTheme, extends: DefaultTheme,
Layout, Layout,
@ -14,5 +19,17 @@ export default {
// }, // },
enhanceApp({ app, router, siteData }) { 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 } satisfies Theme

View File

@ -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])
}