我正在尝试将UTM参数从我的facebook广告传递到网站上的所有页面。
示例查询字符串:www.mysite.com/?utm__source=facebook&utm_medium=psocial&utm_campaign=summer&utm_content=pool&fbclid=1234Jfshio
通常,utm参数将出现在用户访问的第一页上,但是一旦导航到新页面,查询字符串就会丢失。
我希望将查询字符串附加到用户在其会话期间导航到的所有页面上URL的末尾。
我必须这样做,以便他们在与我们的LiveChat服务打开聊天时,我们的服务捕获的起始URL包含他们点击的广告中的utm参数。
这是我当前正在使用的代码-但无法正常工作:
<script type="text/javascript">
(function() {
var utmInheritingDomain = "brilliance.com", // REPLACE THIS DOMAIN
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_source={{url - utm_source}}", // IN GTM, CREATE A URL VARIABLE utm_source
"utm_medium={{url - utm_medium}}", // IN GTM, CREATE A URL VARIABLE utm_medium
"fbclid={{url - fbclid}}" // IN GTM, CREATE A URL VARIABLE fbclid
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) { // The script is looking for all links with the utmInheritingDomain
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0 ) {
tempParts[0] += "?" + utms.join("&"); // The script adds UTM parameters to all links with the domain you've defined
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
</script>
看起来您需要正确检索查询字符串值。我用this answer更新了您的代码(如下)。注意urlParams.get()
的使用:
<script type="text/javascript">
(function() {
const urlParams = new URLSearchParams(window.location.search);
var utmInheritingDomain = "brilliance.com", // REPLACE THIS DOMAIN
utmRegExp = /(\&|\?)utm_[A-Za-z]+=[A-Za-z0-9]+/gi,
links = document.getElementsByTagName("a"),
utms = [
"utm_source=" + urlParams.get('utm_source'), // IN GTM, CREATE A URL VARIABLE utm_source
"utm_medium=" + urlParams.get('utm_medium'), // IN GTM, CREATE A URL VARIABLE utm_medium
"fbclid=" + urlParams.get( 'fbclid' ) // IN GTM, CREATE A URL VARIABLE fbclid
];
for (var index = 0; index < links.length; index += 1) {
var tempLink = links[index].href,
tempParts;
if (tempLink.indexOf(utmInheritingDomain) > 0) { // The script is looking for all links with the utmInheritingDomain
tempLink = tempLink.replace(utmRegExp, "");
tempParts = tempLink.split("#");
if (tempParts[0].indexOf("?") < 0 ) {
tempParts[0] += "?" + utms.join("&"); // The script adds UTM parameters to all links with the domain you've defined
} else {
tempParts[0] += "&" + utms.join("&");
}
tempLink = tempParts.join("#");
}
links[index].href = tempLink;
}
}());
</script>