DIV CSS 佈局教程網

用 JavaScript 精確統計網站訪問量:完整腳本解析
編輯:關於JavaScript     

這份腳本示範如何在前端收集訪問資訊並回報給伺服器。核心機制是:用 cookie 為每位訪客配發一個唯一識別碼,再搭配瀏覽器環境資訊,以 GET 請求把資料送到統計端點。

/**
 * vlstat 瀏覽器統計腳本
 */
var statIdName = "vlstatId";
var xmlHttp;

/**
 * 設定 cookie
 */
function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value)
        + ((expiredays == null) ? "" : ";expires=" + exdate.toGMTString())
        + ";path=/;domain=cecb2b.com";
}

/**
 * 讀取 cookie
 */
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

/**
 * 取得當前時間戳
 */
function getTimestamp() {
    return Date.parse(new Date());
}

/**
 * 產生 statId
 */
function genStatId() {
    var cookieId = getTimestamp();
    cookieId = "vlstat" + "-" + cookieId + "-" + Math.round(Math.random() * 3000000000);
    return cookieId;
}

/**
 * 寫入 statId
 */
function setStatId() {
    setCookie(statIdName, genStatId(), 365);
}

/**
 * 取得 statId,沒有就產生一個
 */
function getStatId() {
    var statId = getCookie(statIdName);
    if (statId != null && statId.length > 0) {
        return statId;
    } else {
        setStatId();
        return getStatId();      // 遞迴取回剛寫入的值
    }
}

/**
 * 取得 User-Agent,過長則截斷
 */
function getUA() {
    var ua = navigator.userAgent;
    if (ua.length > 250) {
        ua = ua.substring(0, 250);
    }
    return ua;
}

/**
 * 判斷瀏覽器類型
 */
function getBrower() {
    var ua = getUA();
    if (ua.indexOf("Maxthon") != -1)      { return "Maxthon"; }
    else if (ua.indexOf("MSIE") != -1)    { return "MSIE"; }
    else if (ua.indexOf("Firefox") != -1) { return "Firefox"; }
    else if (ua.indexOf("Chrome") != -1)  { return "Chrome"; }
    else if (ua.indexOf("Opera") != -1)   { return "Opera"; }
    else if (ua.indexOf("Safari") != -1)  { return "Safari"; }
    else                                  { return "ot"; }
}

/**
 * 取得瀏覽器語言
 */
function getBrowerLanguage() {
    var lang = navigator.browserLanguage;
    return lang != null && lang.length > 0 ? lang : "";
}

/**
 * 取得作業系統平台
 */
function getPlatform() {
    return navigator.platform;
}

/**
 * 取得頁面標題
 */
function getPageTitle() {
    return document.title;
}

/**
 * 建立一個 POST 用的表單
 */
function createSubmitForm() {
    var frm = document.createElement("form");
    document.body.appendChild(frm);
    frm.method = "POST";
    return frm;
}

/**
 * 為表單建立隱藏欄位
 */
function createFormElement(frmInput, elementName, elementValue) {
    var element = document.createElement("input");
    element.setAttribute("id", elementName);
    element.setAttribute("name", elementName);
    element.setAttribute("type", "hidden");
    element.setAttribute("value", elementValue);
    frmInput.appendChild(element);
    return element;
}

/**
 * 建構 XMLHttpRequest 物件(相容舊 IE)
 */
function createXMLHttpRequest() {
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
    } else if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    }
}

/**
 * url 為目標端點,data 為要 POST 的內容,func 相當於函數指標
 */
function AjaxPost(url, data, func) {
    var httpRequest = createHttpRequest();
    if (httpRequest) {
        httpRequest.open("POST", url, true);
        httpRequest.setRequestHeader("content-length", data.length);
        httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        httpRequest.send(data);

        httpRequest.onreadystatechange = function () {
            if (httpRequest.readyState == 4) {
                try {
                    if (httpRequest.status == 200) {
                        if (func) {
                            func(httpRequest.responseText);
                        }
                    }
                } catch (e) {
                    alert("Error XMLHttpRequest!");
                }
            }
        };
    } else {
        alert("Error initializing XMLHttpRequest!");
    }
}

function vlstatInitLE(vlch, vlch1, vlch2, vlch3) {
    var vlstatCH  = vlch  != null && vlch.length  > 0 ? vlch  : "";
    var vlstatCH1 = vlch1 != null && vlch1.length > 0 ? vlch1 : "";
    var vlstatCH2 = vlch2 != null && vlch2.length > 0 ? vlch2 : "";
    var vlstatCH3 = vlch3 != null && vlch3.length > 0 ? vlch3 : "";

    var p = "cookieId="  + getStatId()
          + "&ua="        + encodeURIComponent(getUA())
          + "&ip="        + document.localName
          + "&refurl="   + encodeURIComponent(document.referrer)
          + "&url="      + encodeURIComponent(document.URL)
          + "&screenX="  + screen.width
          + "&screenY="  + screen.height
          + "&os="       + getPlatform()
          + "&brower="   + getBrower()
          + "&browerLang=" + getBrowerLanguage()
          + "&title="    + encodeURIComponent(getPageTitle())
          + "&ch="  + vlstatCH
          + "&ch1=" + vlstatCH1
          + "&ch2=" + vlstatCH2
          + "&ch3=" + vlstatCH3;

    var urlGo = "index.php?" + p;
    createXMLHttpRequest();
    xmlHttp.open('GET', urlGo);
    xmlHttp.send(null);
}

運作流程

進入頁面後呼叫 vlstatInitLE(),它會先用 getStatId() 取得訪客識別碼:cookie 裡有就重用,沒有就即時產生一組「時間戳 + 隨機數」寫入 cookie,有效期一年。接著收集 User-Agent、來源頁、當前網址、螢幕解析度、平台、瀏覽器、語言、標題等資訊,全部用 encodeURIComponent 編碼後拼成查詢字串,以 GET 送到 index.php 由後端入庫。

這個設計的關鍵在於 cookieId 的持久化:同一個訪客反覆造訪時識別碼不變,後端就能區分「總瀏覽量」與「獨立訪客數」。少了這一步,重新整理都會被算成新訪客。

這份程式碼今天不建議照抄

UA 判斷順序有 bug。Chrome 的 User-Agent 裡同時含有 Safari,所以 Chrome 必須排在 Safari 之前判斷——示範碼順序剛好正確,但這類清單式的判斷本身就脆弱,現代做法應改用 navigator.userAgentData 或功能偵測。

navigator.browserLanguage 已非標準。應該改用 navigator.language 或 navigator.languages。

document.localName 取不到 IP。它回傳的是文件元素的本地名稱,跟網路位址毫無關係。真正的用戶 IP 只能由伺服器從連線資訊中取得,前端拿不到,也不該嘗試拿。

用 GET 傳送大量資料不合適。網址有長度上限,中文標題編碼後很容易撐爆。改用 fetch() 發 POST,或用 navigator.sendBeacon()——後者專為統計這類「送出後不需要回應」的情境設計,即使頁面正在卸載也能可靠送達。

escape / unescape 已廢棄。請改用 encodeURIComponent 與 decodeURIComponent,前者對非 ASCII 字元的處理是錯誤的。

隱私與法規。在前端收集並回傳使用者環境資訊屬於個人資料處理,實作時必須明確告知並取得同意,例如 GCP、GDPR 等規範都要求可拒絕、可查閱。這不只是技術問題,也是合規問題。

如果只是想快速接入統計,直接掛 Google Analytics 或類似服務的官方片段會省下大量維護成本;自建方案的價值在於資料完全自有、可客製指標,那時值得用正規的後端收集管道重寫一遍。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved