vercel / analytics

Privacy-friendly, real-time traffic insights
https://vercel.com/analytics
Mozilla Public License 2.0
422 stars 26 forks source link

Analytics treats in-page anchor jumps as pageviews #51

Closed Justineo closed 1 year ago

Justineo commented 1 year ago

There seems to be a potential bug in /_vercel/analytics/script.js:

history.pushState = function(...t) {
    let n = t[2]
      , i = "string" == typeof n ? location.pathname !== n.split("?")[0] : n && location.href !== n.href;
    e(...t),
    i && r()
}

It is comparing pathname with the target URL apart from the search part. But for target URLs like /foo#bar it will be count as a new page view. And I'm also aware that if we strip hashes as well this may break the use case for those SPAs with hash router. So I think we should expose an option to let users to configure their routing behavior.

tobiaslins commented 1 year ago

Hey @Justineo :)

We consider adding a way to disable automatic page view collection (and triggering them manually). For now you will need to use beforeSend to skip tracking page views with # in the URL.

<Analytics beforeSend={function (event) {
    if(event.url.includes("#")) return 
    return event;
}} />

Something like that would work, but sadly there is no way to find out if it was a crosspage navigation or same page hash navigation. https://vercel.com/docs/concepts/analytics/audiences/redacting-sensitive-data

Justineo commented 1 year ago

I think this workaround won't work as the page view event does not expose enough information. The page view from /foo to /bar#baz shouldn't be skipped.

We need both the URL before navigation and after it to see if history change is caused by in-page anchors but in current implementation we only got url.

https://github.com/vercel/analytics/blob/73e33e72bfca3d68ee12d2f987b36d7f04cd77c6/packages/web/src/types.ts#L1-L4

Justineo commented 1 year ago

Hello, I'm following up on the status of this issue. Has there been any progress?

tobiaslins commented 1 year ago

@Justineo You could keep the previous page in useRef and only skip the event when its a same page navigation! What do you think?

Justineo commented 1 year ago

I think this is a common use case and shouldn’t require such workaround. Technically we can rewrite any client side logic but I think it should be handled by the analytics SDK itself.

tobiaslins commented 1 year ago

We just rolled out a new version that now doesn't track same-page hash navigations anymore! This should work now as expected without any changes on your side!

Thanks 🙏