PaiGramDocs/docs/.vitepress/theme/plugins/baidutongji.ts

50 lines
1.1 KiB
TypeScript
Raw Normal View History

2023-10-20 17:15:41 +00:00
import { inBrowser } from 'vitepress'
/**
* ID
*/
export const siteIds = 'eb1ef90b1e9476b8d3d43088d3ac9c49'
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])
}