[英]Javascript redirect - With Analytics
我正在嘗試跟蹤有多少用戶通過一個營銷渠道訪問我的網站。 客戶會收到一個 url,專門針對該廣告,然后 url 會將用戶發送到實際站點。 在此過程中跟蹤他們。 我並不完全有信心這樣做:
//Include jQuery
<script language="text/javascript" src="jquery.js">
<script language="text/javascript">
//Get IP address to block (ours)
var clientip = "<?php echo $_SERVER['REMOTE_ADDR']; ?>";
$(document).ready(function() {
//If IP is forbidden
if(clientip == "xxx.xxx.xxx.xxx")
{
alert("Redirect has been disabled for you");
} else {
//GOOGLE ANALYTICS CODE
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//Redirect User
window.location = 'http://www.companysite.co.uk';
}
});
</script>
如果用戶的 IP 與禁止的不匹配,則此代碼應該僅運行分析代碼。
您應該只需要每頁加載一次 GA。 加載 GA 后,您可以傳遞其他事件/操作,如下所示:
_gaq.push(['_setAccount','UA-XXXXXXXX-X']);
_gaq.push(['_trackPageview','/item/to/track']);
當然,這應該可行,但是如果您要像這樣混合服務器端和客戶端代碼,為什么不首先將服務器端代碼用於 output 一個客戶端代碼或另一個. 就像是
<!--Include jQuery-->
<script language="text/javascript" src="jquery.js">
<script language="text/javascript">
$(document).ready(function() {
<?php
if ($_SERVER['REMOTE_ADDR'] == 'xxx.xxx.xxx.xxx') {
?>
alert("Redirect has been disabled for you");
<?php
} else {
?>
//GOOGLE ANALYTICS CODE
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
//Redirect User
window.location = 'http://www.companysite.co.uk';
<?php
}
?>
});
</script>
不過還有一件事..您可能應該將 window.location 包裝在 500-1000 毫秒的 setTimeout() 中,以使 GA 代碼有機會在重定向之前執行。
雖然這會起作用,但有人很容易繞過重定向,因為它只是用 JavaScript 編寫的。 您最好在服務器上進行重定向。
此外,您不需要這么復雜的東西來從跟蹤中排除 IP,因為您可以在 GA 中的配置文件上使用排除過濾器。 Go 到配置文件設置,然后添加具有以下設置的過濾器:
然后輸入要排除的 IP。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.