Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JSON visitor counter doesn't work because of CORS header #782

Closed
subins2000 opened this issue Dec 13, 2024 · 2 comments
Closed

JSON visitor counter doesn't work because of CORS header #782

subins2000 opened this issue Dec 13, 2024 · 2 comments

Comments

@subins2000
Copy link

<div>Number of visitors: <div id="stats"></div></div>

<script>
    var r = new XMLHttpRequest();
    r.addEventListener('load', function() {
        document.querySelector('#stats').innerText = JSON.parse(this.responseText).count
    })
    r.open('GET', 'https://subinsbdotcom.goatcounter.com/counter/' + encodeURIComponent(location.pathname) + '.json')
    r.send()
</script>

Screenshot_20241214_044401

@jbhoot
Copy link

jbhoot commented Feb 28, 2025

You seem to have run into the same problem I faced yesterday.

The URL in the screenshot contains an extra encoded trailing slash, represented by %2F, right before .json.

What you want is https://subinsbdotcom.goatcounter.com/counter/talks.json.
But what you have is https://subinsbdotcom.goatcounter.com/counter//talks/.json.

//talks is not a problem, but talks/.json is.

I updated the relevant code to remove trailing slash, if any, right before .json:

r.open('GET', 'https://subinsbdotcom.goatcounter.com/counter/' + encodeURIComponent(location.pathname.replace(/\/$/, "")) + '.json')

Specifically, encodeURIComponent(location.pathname) becomes encodeURIComponent(location.pathname.replace(/\/$/, "")).

@arp242 arp242 closed this as completed in 21250cb Mar 19, 2025
arp242 added a commit that referenced this issue Mar 19, 2025
Also expose get_data() from count.js, so you can use the same code.

Ref: #782
@arp242
Copy link
Owner

arp242 commented Mar 19, 2025

The core problem is that it's a 404: that is, the path isn't known in GoatCounter (in this case, probably due to that slash). It should now also set the CORS header on 404 errors.

The URL should be:

/counter/«PATH».json

Where «PATH» is the exact path as it appears in the dashboard. This should always start with a / (although I think it's added automatically if you omit it). For some people, the path should end with a /.

I updated the docs a bit to clarify. I also exposed get_data() from count.js, so you can get the path from there:

let path = window.goatcounter.get_data()['p']

r.open('GET', 'http://stats.example.com/counter/' + encodeURIComponent(path) + '.json')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants