最近在主导重构公司一款国际化产品,需要进行埋点统计,具体需求是工程里面的事件分析根据国内/国外进行统计,海外版的使用谷歌统计,国内版的采用百度统计。采用的是同一套工程代码,所以只需要写一个方法,里面根据配置文件的平台属性来做区分是百度统计还是谷歌统计,代码总结如下:
;(function (win) { var config = win.SYSTEM_CONFIG; var statistics = function () { }; if (config && (config.baidu || config.google)) { var platform = config.platform; if (platform === ‘国内‘) { var _hmt = _hmt || []; (function () { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?" + config.baidu;//百度统计的key var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); statistics = function (category, action, opt_label, opt_value) { //_hmt.push([‘_trackEvent‘, category, action, opt_label, opt_value]); _hmt.push([‘_trackEvent‘, category, action, opt_label || "", opt_value || 1]); } } else if (platform === ‘海外‘) { /*- Global site tag (gtag.js) - Google Analytics --*/ document.write(‘<script async src = "https://www.googletagmanager.com/gtag/js?id=‘ + config.google + ‘" > <‘ + ‘/script>‘);//谷歌统计的key window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments); } gtag(‘js‘, new Date()); gtag(‘config‘, config.google); statistics = function (category, action, opt_label, opt_value) { gtag(‘event‘, action, { ‘event_category‘: category, ‘event_label‘: opt_label || "", value: opt_value || 1 }); } } } window.Statistics = statistics; })(window);
原文地址:https://www.cnblogs.com/keang001/p/8949744.html
时间: 2024-10-13 21:20:21