最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Is it possible to use JavaScript to track how many page views in past 24 hours? - Stack Overflow

programmeradmin0浏览0评论

I need to track how many users have visited some page in the past 24 hours, and if the number of users goes over 50 in this time, then I want to display the dynamically summed cumulative user count for that timeframe.

I have previously used a basic bination of JS POST and PHP parsing on the back end like this:

    $.post( "//api.link.here/using.php", { someParameter: 'xxx' }, function(data) { 
        if(data > 50) {
            $('#much-visits').html('Hot Like Fire: '+data);
        }
    });

But am now working on a platform that doesn't allow me to edit PHP in any way, and this method has not been developed on this platform.

The Question:

Is it possible to acplish this same/similar thing but with javascript only (frameworks/outside API calls allowed)?

I need to track how many users have visited some page in the past 24 hours, and if the number of users goes over 50 in this time, then I want to display the dynamically summed cumulative user count for that timeframe.

I have previously used a basic bination of JS POST and PHP parsing on the back end like this:

    $.post( "//api.link.here/using.php", { someParameter: 'xxx' }, function(data) { 
        if(data > 50) {
            $('#much-visits').html('Hot Like Fire: '+data);
        }
    });

But am now working on a platform that doesn't allow me to edit PHP in any way, and this method has not been developed on this platform.

The Question:

Is it possible to acplish this same/similar thing but with javascript only (frameworks/outside API calls allowed)?

Share Improve this question edited Jun 20, 2020 at 9:12 CommunityBot 11 silver badge asked May 27, 2015 at 5:40 Andre BulatovAndre Bulatov 1,1393 gold badges17 silver badges50 bronze badges 1
  • What platform are you working on? – aug Commented May 27, 2015 at 5:43
Add a ment  | 

3 Answers 3

Reset to default 4

It's impossible to do it solely using client-side JavaScript, because then you wouldn't have any unified record of how many visitors came to the site. You must have either a server-side element or a third-party element (such as Google Analytics).

Actually, you can! You need jQuery though, so if you can get that, you're good to go!

Every time a person visits the page, execute this function (change usercount to something more unique):

$.ajax({
url:"http://count.io/vb/usercount/users+",
type: "POST"
});

And when you want to read its value, call this function. Usercount is the unique string you made previously:

$.ajax({
url:"http://count.io/vb/usercount/",
success: function(data) {
    alert(data.counts[0].count);
}
});

It's important to know that if someone gets to know the string, they might be able to hack the system so be wary of that.

I figured out how to do this with the help of user kabiroberai's answer regarding count.io.

Every time a person visits the page, execute this function (change usercount to something more unique):

$.ajax({
url:"http://count.io/vb/usercount/users+",
type: "POST"
});

And when you want to read its value, call this function. Usercount is the unique string you made previously:

$.ajax({
url:"http://count.io/vb/usercount/",
success: function(data) {
    alert(data.counts[0].count);
}
});

NOTE: It's important to know that if someone gets to know the string, they might be able to hack the system so be wary of that.

The problem with this method is that it gives us the total count of all time, rather than the count of users from the past 24 hours.

To get the 24-hour count, we can do this: // Timestamp shim for browsers

    // Timestamp
    var timestamp = Math.floor(Date.now());
    // 24 hour old timestampt
    var dayAgo = timestamp - 86400000;

    // Record a hit to the count.io DB under DankStopProduct# group, as a timestmped hit of 1
    var productNumber = $('.some-product-element').find('some-unique-identifier').attr('value'); //Doesn't have to be value, could be any unique identifier
    $.ajax({
        url:'http://count.io/vb/YourProduct' + productNumber + '/' + timestamp + '+',
        type: 'POST'
    });

    // Make dynamic HTTP prefix that depends on the prefi of the site's current page protocol
    var httpPrefix = (window.location.protocol === 'http:' ? 'http:' : 'https:');

    // Retrieve current product array
    $.post(
        //I use CORS-anywhere to retrieve the data as otherwise there is a cross-origin problem
        httpPrefix + '//cors-anywhere.herokuapp./' + 'http://count.io/vb/YourProduct' + productNumber,
        function (data) {
            var timedViewCounter = 0;
            var myStringArray = data.counts;
            var arrayLength = myStringArray.length;
            // Check each "timestamped hit" in the current product's array to see if it's older than 24 hours
            for (var i = 0; i < arrayLength; i++) {
                var itemTimestamp = data.counts[i].item;
                // Count up all the product hits that are 24 hours old or newer
                if (itemTimestamp > dayAgo) {
                    timedViewCounter++;
                }
            }
            // If total count is greater than 50, then output HTML onto page
            var hotItem = '<div id="hot-item"><strong><i class="fa fa-fire"></i> Hot Like Fire!</strong> - ' + 
                            '<span class="view-count">' + timedViewCounter + '</span> people have viewed this product in the last 24 hours</div>';
            if (timedViewCounter > 50) {
                $(".FreeShippingContainer").before(hotItem);
            }
    });

And that's all! Now the product view count will only be output if it's 51 views or higher in the past 24 hours.

发布评论

评论列表(0)

  1. 暂无评论