我正在尝试将UTM参数从我的facebook广告传递到我网站上的所有页面。
查询字符串示例: www.mysite.com/?utm__source=facebook&utm_medium=psocial&utm_campaign=summer&utm_content=pool&fbclid=1234Jfshio
通常,utm参数将存在于用户访问的第一个页面上,但是一旦用户导航到新页面,查询字符串就会丢失。
我希望将查询字符串附加到我的用户在会话期间导航到的所有页面的URL末尾。
我必须这样做,这样当他们使用我们的LiveChat服务打开聊天时,我们的服务捕获的开始网址包含来自他们点击的广告的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>
发布于 2020-03-03 12:24:30
看起来您需要正确检索查询字符串值。我使用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>https://stackoverflow.com/questions/60496840
复制相似问题