Skip to content

Commit

Permalink
Increment count with unique visitor ID stored in localStorage.
Browse files Browse the repository at this point in the history
  • Loading branch information
yasuaki640 committed Apr 23, 2024
1 parent eb7a7f7 commit e30b994
Showing 1 changed file with 28 additions and 1 deletion.
29 changes: 28 additions & 1 deletion assets/js/increment-count.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,34 @@
const STORAGE_KEY = "yasuaki640.github.io-visitorId";
const CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

const generateRandomString = (length) => {
let res = "";
const charLength = CHARS.length;
for (let i = 0; i < length; i++) {
res += CHARS.charAt(Math.floor(Math.random() * charLength));
}

return res;
};

const retrieveVisitorId = () => {
const visitorId = localStorage.getItem(STORAGE_KEY);
if (!visitorId) {
localStorage.setItem(STORAGE_KEY, generateRandomString(16));
}

return visitorId;
};

(async () => {
const res = await fetch(
const visitorId = retrieveVisitorId();

const url = new URL(
"https://page-view-counter-api.yasuaki640.workers.dev/increment-count",
);
url.searchParams.append(STORAGE_KEY, visitorId);

const res = await fetch(url);
const { count } = await res.json();

document.getElementById(
Expand Down

0 comments on commit e30b994

Please sign in to comment.