Public
HTTP (deprecated)
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Readme

Create a simple hit counter that you can attach to any website via fetch .

I created a web component to use this :


export class HitCounter extends HTMLElement {
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      this.count = 0;
      this.fetchCount();
    }
  
    fetchCount() {
      fetch('https://triptych-hitcounter.web.val.run/')
        .then(response => response.json())
        .then(data => {
          this.count = data.siteCount;
          this.render();
        })
        .catch(error => console.error('Error fetching count:', error));
    }
  
    render() {
      const container = document.createElement('div');
      container.style.backgroundColor = 'black';
      container.style.color = 'white';
      container.style.border = '1px solid white';
      container.style.padding = '10px';
      container.style.display = 'inline-block'; // Add this line
      container.textContent = `hit count: ${this.count}`;
  
      this.shadowRoot.appendChild(container);
    }
  }
  
  customElements.define('hit-counter', HitCounter);

1
2
3
4
5
6
7
8
9
10
11
import { blob } from "https://esm.town/v/std/blob";
const KEY = "site_count";
// let hitCount = await blob.getJSON(KEY);
const oldState = await blob.getJSON(KEY) ?? 0;
console.log("Old value", oldState);
await blob.setJSON(KEY, oldState + 1);
const siteCount = await blob.getJSON(KEY);
export default async function(req: Request): Promise<Response> {
return Response.json({ siteCount });
}
triptych-hitcounter.web.val.run
June 7, 2024