feat(plugin-baidu-tongji): add useBaiduTongji

This commit is contained in:
pengzhanbo 2024-02-17 00:20:48 +08:00
parent e707e9a057
commit 9dfa6c976f
3 changed files with 71 additions and 15 deletions

View File

@ -0,0 +1,29 @@
import { watch } from 'vue'
import { usePageData } from 'vuepress/client'
declare global {
interface Window {
_hmt?: [name: string, options: any][]
}
}
/**
* Add baidu analytics to the site
*
* @see https://tongji.baidu.com/
* @see https://tongji.baidu.com/holmes/Analytics/%E7%99%BE%E5%BA%A6%E7%BB%9F%E8%AE%A1%E4%BD%BF%E7%94%A8%E6%89%8B%E5%86%8C
* @see https://tongji.baidu.com/holmes/Analytics/%E6%8A%80%E6%9C%AF%E6%8E%A5%E5%85%A5%E6%8C%87%E5%8D%97/JS%20API/JS%20API%E6%8A%80%E6%9C%AF%E6%96%87%E6%A1%A3/_trackPageview
*/
export function useBaiduTongji(): void {
if (!window._hmt)
return
const page = usePageData()
watch(
() => page.value.path,
(newLocation) => {
window._hmt?.push(['_trackPageview', newLocation])
},
)
}

View File

@ -0,0 +1,14 @@
import { defineClientConfig } from 'vuepress/client'
import type { ClientConfig } from 'vuepress/client'
import { useBaiduTongji } from './composables/index.js'
declare const __VUEPRESS_SSR__: boolean
export default defineClientConfig({
enhance() {
if (__VUEPRESS_SSR__)
return
useBaiduTongji()
},
}) as ClientConfig

View File

@ -1,23 +1,36 @@
import type { Plugin } from 'vuepress/core'
import type { Plugin, PluginObject } from 'vuepress/core'
import { getDirname, path } from 'vuepress/utils'
export interface BaiduTongjiOptions {
key?: string
}
const __dirname = getDirname(import.meta.url)
export function baiduTongjiPlugin({ key = '' }: BaiduTongjiOptions): Plugin {
return {
name: '@vuepress-plume/plugin-baidu-tongji',
extendsPage: (page) => {
page.frontmatter.head ??= []
page.frontmatter.head?.push([
'script',
{ type: 'text/javascript' },
'var _hmt = _hmt || []',
])
page.frontmatter.head?.push([
'script',
{ src: `https://hm.baidu.com/hm.js?${key}` },
])
},
return (app) => {
const plugin: PluginObject = {
name: '@vuepress-plume/plugin-baidu-tongji',
}
if (app.env.isDev)
return plugin
return {
...plugin,
clientConfigFile: path.resolve(__dirname, '../client/config.js'),
extendsPage: (page) => {
page.frontmatter.head ??= []
page.frontmatter.head?.push([
'script',
{ type: 'text/javascript' },
'window._hmt = window._hmt || []',
])
page.frontmatter.head?.push([
'script',
{ src: `https://hm.baidu.com/hm.js?${key}`, async: true },
])
},
}
}
}