index.ts 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import { onMounted } from 'vue'
  2. import { useGlobalStore } from '@/stores'
  3. import plus from '@/utils/h5plus'
  4. // https://developers.facebook.com/docs/meta-pixel/reference
  5. declare global {
  6. interface Window {
  7. fbq: any;
  8. _fbq: any;
  9. }
  10. }
  11. export function useMetaPixel() {
  12. const { getSystemInfo } = useGlobalStore()
  13. const pixelId = getSystemInfo('metaPixelId')
  14. // 初始化 MetaPixel
  15. const initPixel = () => {
  16. if (pixelId) {
  17. if (window.fbq) return
  18. const fbq: any = <T>(...args: T[]) => {
  19. fbq.callMethod
  20. ? fbq.callMethod(...args)
  21. : fbq.queue.push(args)
  22. }
  23. if (!window._fbq) {
  24. window._fbq = fbq
  25. }
  26. fbq.push = fbq
  27. fbq.loaded = true
  28. fbq.version = '2.0'
  29. fbq.queue = []
  30. const el = document.createElement('script')
  31. el.async = true
  32. el.src = 'https://connect.facebook.net/en_US/fbevents.js'
  33. const tag = document.getElementsByTagName('script')[0]
  34. tag.parentNode?.insertBefore(el, tag)
  35. window.fbq = fbq
  36. window.fbq('init', pixelId)
  37. }
  38. }
  39. // 跟踪页面视图
  40. const trackPageView = () => {
  41. if (pixelId) {
  42. window.fbq('track', 'PageView')
  43. }
  44. }
  45. // 跟踪自定义事件
  46. const trackEvent = (eventName: 'Lead' | 'Purchase', parameters?: Record<string, any>) => {
  47. // if (pixelId) {
  48. // window.fbq('track', eventName, parameters)
  49. // }
  50. plus.onPlusReady((plus) => {
  51. plus.bridge.exec('FacebookExpand', 'expandFunction', [])
  52. })
  53. }
  54. // 在组件挂载时初始化
  55. onMounted(() => {
  56. initPixel()
  57. trackPageView()
  58. })
  59. return {
  60. trackEvent
  61. }
  62. }