How To Add Visitors Counter on Hexo

-- Pageviews

Add Visitors Counter on Hexo

Firebase

Register account on Firebase [here]
Create new project [here]

Get your Firebase configs

Firebase - Get configs - 1 Firebase - Get configs - 2

Modify permission

Firebase - Modify permission

Hexo

Create custom.js

File path: themes\*{your theme}*\source\js\src\custom.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
$(function () {
// Initialize Firebase
var config = {
apiKey: "{your apiKey}",
authDomain: "{your authDomain}",
databaseURL: "{your databaseURL}",
};
firebase.initializeApp(config);

var database = firebase.database();
var oriUrl = window.location.host;
var curUrl = oriUrl + window.location.pathname;
function readVisits(url, selector) {
var db_key = decodeURI(url.replace(new RegExp('\\/|\\.', 'g'), "_"));
database.ref(db_key).once("value").then(function (result) {
var count = parseInt(result.val() || 0) + 1;
database.ref(db_key).set(count);
if (selector.length > 0) {
selector.html(count);
};
});
}
readVisits(oriUrl, $("#visits .count"));
if (curUrl && curUrl != "_") {
readVisits("page/" + curUrl, $("#pageviews .count"));
}
});

Modify layout

Add below html to layout, in themes\*{your theme}*\layout\{where you want to show}.

1
2
<span id="visits">Visits: <font class="count">--<font></span>
<span id="pageviews">Pageviews: <font class="count">--<font></span>

Add references

Add below references to layout footer, must after jquery reference.

1
2
<script src="https://www.gstatic.com/firebasejs/3.6.1/firebase.js"></script>
<script src="js/src/custom.js"></script>

Demo

Add Visitors Counter on Hexo