Gatsby: Don't trigger onRouteUpdate on hash updates

Created on 2 Oct 2017  ·  3Comments  ·  Source: gatsbyjs/gatsby

I export an onRouteUpdate from gatsby-browser.js like so:

export const onRouteUpdate = ({ location, action }) => {
    if (
        window.location &&
        typeof window.location.href === 'string' &&
        window.location.href.includes('www.example.com') // make sure we're on live site
    ) {
        window.analytics.page();
    } else {
        console.log('PAGE: ', window.location.href, action, location);
    }
    return;
};

This works fine, but when there are anchor links on a page, it fires every time one of them is clicked.

I tried just firing the page() on action === 'PUSH' route updates, but that blocks the event on all initial page loads.

Any way to remove anchor link events from this tracking?

documentation question or discussion

All 3 comments

Hi @brandonmp Maybe check in window.location.href if # character is present ?

@sebastienfi he's saying that a hash update (what happens when you click on an anchor) shouldn't trigger the onRouteUpdate API. Which seems pretty reasonable to me. Hash updates should only occur within a single page where the API is intended to be triggered only when switching pages.

@brandonmp would love a PR filtering out hash changes within the same page here! https://github.com/gatsbyjs/gatsby/blob/84362074df2238e6794bb6a056e0163ac1c0dfdd/packages/gatsby/cache-dir/production-app.js#L112

Perhaps put the function in a different file and add a few tests?

Not sure when but we don't fire onRouteUpdate on route changes any more.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kalinchernev picture kalinchernev  ·  3Comments

andykais picture andykais  ·  3Comments

magicly picture magicly  ·  3Comments

benstr picture benstr  ·  3Comments

hobochild picture hobochild  ·  3Comments