使用 cookie 中的值修改页面内容 - Google 跟踪代码管理器
Using values in a cookie to amend page content - Google Tag Manager
我有一个 cookie,当有人访问我网站上的某些页面时,它会存储值(由 | 分隔),即:
产品|50|英国
我想使用 Google 跟踪代码管理器中的自定义 HTML 代码来使用 cookie 中的值修改另一个页面上的内容。
即我有一个 <h2>Old Title</h2>
,我想将其修改为 <h2>Title</h2>
,其中 'Title' 是我 cookie 中第一个分隔字符串的值。
我知道我可能需要使用 jQuery 到 select 页面上的正确元素;但是如何用 cookie 中的值重写它?
如有任何帮助,我们将不胜感激。
我已经在我的网站上成功测试了以下代码。请注意,此代码将 cookie 值写入 first h2 元素。由于我不知道您的网站是什么样子,因此可能会有所更改。
您必须将此代码放入自定义 HTML 标签中。您还必须在 Google 跟踪代码管理器中添加触发器 "DOM Ready",以确保该元素可用。
<script>
// extract the cookieValue
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var cookieValue = getCookie("nameOfYourCookie");
var cookieSplit = cookieValue.split("|")[0];
// Write the Cookie-Value into the first h2 Element
function changeTitle(){
document.getElementsByTagName("h2")[0].innerHTML = cookieSplit;
}
changeTitle();
</script>
我有一个 cookie,当有人访问我网站上的某些页面时,它会存储值(由 | 分隔),即:
产品|50|英国
我想使用 Google 跟踪代码管理器中的自定义 HTML 代码来使用 cookie 中的值修改另一个页面上的内容。
即我有一个 <h2>Old Title</h2>
,我想将其修改为 <h2>Title</h2>
,其中 'Title' 是我 cookie 中第一个分隔字符串的值。
我知道我可能需要使用 jQuery 到 select 页面上的正确元素;但是如何用 cookie 中的值重写它?
如有任何帮助,我们将不胜感激。
我已经在我的网站上成功测试了以下代码。请注意,此代码将 cookie 值写入 first h2 元素。由于我不知道您的网站是什么样子,因此可能会有所更改。
您必须将此代码放入自定义 HTML 标签中。您还必须在 Google 跟踪代码管理器中添加触发器 "DOM Ready",以确保该元素可用。
<script>
// extract the cookieValue
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var cookieValue = getCookie("nameOfYourCookie");
var cookieSplit = cookieValue.split("|")[0];
// Write the Cookie-Value into the first h2 Element
function changeTitle(){
document.getElementsByTagName("h2")[0].innerHTML = cookieSplit;
}
changeTitle();
</script>