Sr.*_*der 3 javascript php regex google-analytics
我使用 UTM 参数来跟踪 Google Analytics 中的传入链接。
假设我的 URL 看起来像这样
https://www.domain.tld/shop?utm_source=newsletter&utm_medium=email&utm_campaign=spring_sale
Run Code Online (Sandbox Code Playgroud)
我想清理 URL。想要的结果是
https://www.domain.tld/shop
Run Code Online (Sandbox Code Playgroud)
在网上我找到了以下片段
(function() {
var win = window;
var removeUtms = function(){
var location = win.location;
if (location.search.indexOf('utm_') != -1 && history.replaceState) {
history.replaceState({}, '', window.location.toString().replace(/(\&|\?)utm([_a-z0-9=]+)/g, ""));
}
};
ga('send', 'pageview', { 'hitCallback': removeUtms });
})();
Run Code Online (Sandbox Code Playgroud)
目前,我的 CMS 中的 Google Analytics 模板如下所示
<?php
/**
* To use this script, please fill in your Google Analytics ID below
*/
$GoogleAnalyticsId = 'UA-bla-bla';
/**
* DO NOT EDIT ANYTHING BELOW THIS LINE UNLESS YOU KNOW WHAT YOU ARE DOING!
*/
if ($GoogleAnalyticsId != 'UA-XXXXX-X' && !BE_USER_LOGGED_IN && sha1(session_id() . (!Config::get('disableIpCheck') ? Environment::get('ip') : '') . 'BE_USER_AUTH') != Input::cookie('BE_USER_AUTH')): ?>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '<?php echo $GoogleAnalyticsId; ?>', 'auto');
<?php if ($GLOBALS['TL_CONFIG']['privacyAnonymizeGA']): ?>
ga('set', 'anonymizeIp', true);
<?php endif; ?>
ga('send', 'pageview');
</script>
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)
...我不知道如何将这些代码组合在一起。
也许我的问题有更好的解决方案?
这是我想出的一个解决方案,它使用History API从以utm_. 重要的是在页面浏览数据通过 utm 参数发送到 Google Analytics后更改 URL 。为此,我们使用带有回调的ga函数并将其放在对 的调用之后,这通常是 Google Analytics 跟踪代码段的最后一行。我使用了而不是这样,如果用户导航回此页面,则 utm 参数将不再出现。这基本上假设您只想报告带有 utm 参数的请求一次ga('send', 'pageview')history.replaceStatehistory.pushState。我相信这适合大多数情况。我进行了功能检查,因此如果history.replaceState 浏览器不支持。
// -- Google Analytics tracking snippet here --
// ...
// ga('send', 'pageview');
/**********************************************************************
* add the following code after the Google Analytics tracking snippet *
**********************************************************************/
// remove utm_* query parameters
ga(function() {
function paramIsNotUtm(param) { return param.slice(0, 4) !== 'utm_'; }
if (history && history.replaceState && location.search) {
var params = location.search.slice(1).split('&');
var newParams = params.filter(paramIsNotUtm);
if (newParams.length < params.length) {
var search = newParams.length ? '?' + newParams.join('&') : '';
var url = location.pathname + search + location.hash;
history.replaceState(null, null, url);
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6146 次 |
| 最近记录: |