• Resolved ads97129

    (@ads97129)


    Hi,

    Since I witched from server side tracking to client side tracking, number of visitors decreased.

    Moreover, my website is based on ajax navigation. The plugin doesn’t count views on pages and an error appears in console: Uncaught SyntaxError: redeclaration of let WP_Statistics_CheckTime. If I reload each page, the plugin counts views.

    Thanks in advance and regards,

Viewing 12 replies - 1 through 12 (of 12 total)
  • Plugin Author Mostafa Soufi

    (@mostafas1990)

    The differences in tracking accuracy are understandable, as client-side tracking tends to be more precise than server-side tracking.

    Regarding the Javascript error you’re experiencing, could you please confirm that you’re using the latest version of WP Statistics? If possible, could you also provide your website URL? we can also review the issue in your website.

    Best

    Thread Starter ads97129

    (@ads97129)

    Hi,

    Thank you for your help.

    I confirm that I’m using lastest version of WP Statistics (14.9.4). The website URL is https://www.archipel-des-sciences.org.

    Regards,

    Plugin Author Mostafa Soufi

    (@mostafas1990)

    Thank you for the update; this makes it easier to debug. Could you please disable the ‘Bypass Ad-Blocker’ option and check if the JavaScript error no longer appears?

    Additionally, one key difference with client-side tracking is that it respects Cookie Consent plugins. This is why some visitors may choose not to have their visits recorded.

    By the way, could you let me know which plugin you’re using for cookie consent?

    Thread Starter ads97129

    (@ads97129)

    I have disabled the ‘Bypass Ad-Blocker’ option but the javascript error still appears in console.

    I’m using Cookie Notice & Compliance for GDPR / CCPA plugin.

    Thanks

    Plugin Author Mostafa Soufi

    (@mostafas1990)

    Let us to have a quite test with that plugin “Cookie Notice & Compliance for GDPR / CCPA” and will get back to you.

    Plugin Support Amir

    (@amirfallah)

    Hi @ads97129

    Since your website content is being loaded via AJAX on different pages, it’s better to use Server Side Tracking instead of relying on Client Side Tracking.

    This approach will help you avoid issues like the one you’re experiencing, as server side tracking doesn’t depend on how your content is loaded on the front end.

    If you want to use Client Side Tracking, changes need to be made to the tracker.js file to resolve the issue.
    For example, you can modify the tracker.js with the sample code below.

    if (typeof WP_Statistics_Tracker_Object == "undefined") {
    let WP_Statistics_CheckTime = WP_Statistics_Tracker_Object.jsCheckTime;

    // Check DoNotTrack Settings on User Browser
    let WP_Statistics_Dnd_Active = parseInt(navigator.msDoNotTrack || window.doNotTrack || navigator.doNotTrack, 10);

    // Prevent init() from running more than once
    let hasTrackerInitializedOnce = false;

    const referred = encodeURIComponent(document.referrer);

    let wpStatisticsUserOnline = {
    hitRequestSuccessful: true, // Flag to track hit request status

    init: function () {
    if (hasTrackerInitializedOnce) {
    return;
    }
    hasTrackerInitializedOnce = true;

    if (typeof WP_Statistics_Tracker_Object == "undefined") {
    console.error('WP Statistics: Variable WP_Statistics_Tracker_Object not found. Ensure /wp-content/plugins/wp-statistics/assets/js/tracker.js is either excluded from cache settings or not dequeued by any plugin. Clear your cache if necessary.');
    } else {
    this.checkHitRequestConditions();

    if (WP_Statistics_Tracker_Object.option.userOnline) {
    this.keepUserOnline();
    }
    }
    },

    // Check Conditions for Sending Hit Request
    checkHitRequestConditions: function () {
    if (WP_Statistics_Tracker_Object.option.dntEnabled) {
    if (WP_Statistics_Dnd_Active !== 1) {
    this.sendHitRequest();
    } else {
    console.log('WP Statistics: Do Not Track (DNT) is enabled. Hit request not sent.');
    }
    } else {
    this.sendHitRequest();
    }
    },

    // Sending Hit Request
    sendHitRequest: async function () {
    try {
    let requestUrl = this.getRequestUrl('hit');
    const params = new URLSearchParams({
    ...WP_Statistics_Tracker_Object.hitParams,
    referred
    }).toString();

    const xhr = new XMLHttpRequest();
    xhr.open('POST', requestUrl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
    xhr.onreadystatechange = function () {
    if (xhr.readyState === 4) {
    if (xhr.status === 200) {
    const responseData = JSON.parse(xhr.responseText);
    this.hitRequestSuccessful = responseData.status !== false;
    } else {
    this.hitRequestSuccessful = false;
    console.warn('WP Statistics: Hit request failed with status ' + xhr.status);
    }
    }
    }.bind(this);
    } catch (error) {
    this.hitRequestSuccessful = false;
    console.error('WP Statistics: Error sending hit request:', error);
    }
    },

    // Send Request to REST API to Show User Is Online
    sendOnlineUserRequest: async function () {
    if (!this.hitRequestSuccessful) {
    return; // Stop if hit request was not successful
    }

    try {
    let requestUrl = this.getRequestUrl('online');
    const params = new URLSearchParams({
    ...WP_Statistics_Tracker_Object.onlineParams,
    referred
    }).toString();

    const xhr = new XMLHttpRequest();
    xhr.open('POST', requestUrl, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send(params);
    } catch (error) {

    }
    },

    // Execute Send Online User Request Function Every n Sec
    keepUserOnline: function () {
    let userActivityTimeout;

    if (!WP_Statistics_Tracker_Object.option.userOnline) {
    return; // Stop if userOnline option is false
    }

    const userOnlineInterval = setInterval(
    function () {
    if ((!WP_Statistics_Tracker_Object.option.dntEnabled || (WP_Statistics_Tracker_Object.option.dntEnabled && WP_Statistics_Dnd_Active !== 1)) && this.hitRequestSuccessful) {
    this.sendOnlineUserRequest();
    }
    }.bind(this), WP_Statistics_CheckTime
    );

    // After 30 mins of inactivity, stop keeping user online
    ['click', 'keypress', 'scroll', 'DOMContentLoaded'].forEach(event => {
    window.addEventListener(event, () => {
    clearTimeout(userActivityTimeout);

    userActivityTimeout = setTimeout(() => {
    clearInterval(userOnlineInterval);
    }, 30 * 60 * 1000);
    });
    });
    },

    getRequestUrl: function (type) {
    let requestUrl =
    ${WP_Statistics_Tracker_Object.requestUrl}/;

    if (WP_Statistics_Tracker_Object.option.bypassAdBlockers) {
    requestUrl = WP_Statistics_Tracker_Object.ajaxUrl;
    } else {
    if (type === 'hit') {
    requestUrl += WP_Statistics_Tracker_Object.hitParams.endpoint;
    } else if (type === 'online') {
    requestUrl += WP_Statistics_Tracker_Object.onlineParams.endpoint;
    }
    }

    return requestUrl;
    },
    };

    document.addEventListener('DOMContentLoaded', function () {
    if (WP_Statistics_Tracker_Object.option.consentLevel == 'disabled' || WP_Statistics_Tracker_Object.option.trackAnonymously ||
    !WP_Statistics_Tracker_Object.option.isWpConsentApiActive || wp_has_consent(WP_Statistics_Tracker_Object.option.consentLevel)) {
    wpStatisticsUserOnline.init();
    }

    document.addEventListener("wp_listen_for_consent_change", function (e) {
    const changedConsentCategory = e.detail;
    for (let key in changedConsentCategory) {
    if (changedConsentCategory.hasOwnProperty(key)) {
    if (key === WP_Statistics_Tracker_Object.option.consentLevel && changedConsentCategory[key] === 'allow') {
    wpStatisticsUserOnline.init();

    // When trackAnonymously is enabled, the init() call above will get ignored (since it's already initialized before)
    // So, in this specific case, we can call checkHitRequestConditions() manually
    // This will insert a new record for the user (who just gave consent to us) and prevent other scripts (e.g. event.js) from malfunctioning
    if (WP_Statistics_Tracker_Object.option.trackAnonymously) {
    wpStatisticsUserOnline.checkHitRequestConditions();
    }
    }
    }
    }
    });
    });
    }

    Please let me know if you have any further questions or need assistance.
    Regards,

    • This reply was modified 3 months, 1 week ago by Amir.
    Thread Starter ads97129

    (@ads97129)

    Hi Amir,

    Thank you for your help.

    I tried new code in tracjer.js. Conole give me error on line 126 : Uncaught SyntaxError: unexpected token: ‘{‘.

    Regards,

    Plugin Author Mostafa Soufi

    (@mostafas1990)

    Btw, where did you apply the changes? in wp-content/uploads/{hash-assets}.js or wp-content/plugins/wp-statistics/assets/js/tracker.js?

    It might be more effective to consult the person who developed the AJAX navigation on your website. The issue can likely be resolved by adjusting the conditions as I suggested.

    Best

    Thread Starter ads97129

    (@ads97129)

    I have applied the changes in wp-content/plugins/wp-statistics/assets/js/tracker.js.

    Regards

    Plugin Author Mostafa Soufi

    (@mostafas1990)

    Sorry for the late reply.

    Can you please tell me what do you use for AJAX navigation?

    Thread Starter ads97129

    (@ads97129)

    Hi,

    I have created myself the ajax navigation.

    As you have recommanded, I decided to use Server Side Tracking. But how can I bypass cache plugin ?

    Thank you for your help.

    Regards

    Plugin Support Amir

    (@amirfallah)

    Hi @ads97129

    As you have implemented AJAX navigation independently and we do not provide support for it, we recommend referring to the code sample we previously shared to help you address the issue.

    In this case, we suggest using Server Side Tracking. This approach will also automatically resolve the caching issue and does not require any specific settings.

    Regards,

Viewing 12 replies - 1 through 12 (of 12 total)
  • You must be logged in to reply to this topic.