使用 next.js 监听路由变化以与 matomo/piwik 一起使用

Listen to route change with next.js to use with matomo/piwik

我正在尝试在 next.js 应用程序上监听路线变化,以便将导航记录到 matomo(又名 piwik)。根据 next.js' 文档,我必须这样做:

Router.events.on('routeChangeStart', url => {
  // Do something
});

我必须在我的应用程序中的什么地方使用此代码才能记录所有路线更改事件?

("where"表示其中file/class/method)

您必须在 pages/_app.js 中添加它,在 componentDidMount 方法中:

componentDidMount() {
  Router.events.on("routeChangeStart", url => {
    if (window && window._paq) {
      window._paq.push(["setCustomUrl", url]);
      window._paq.push(["setDocumentTitle", document.title]);
      window._paq.push(["trackPageView"]);
    }
  });
}

不要忘记 initialize it 在您的基本页面(即您的布局或类似的东西)中:

<!-- Matomo -->
<script type="text/javascript">
  var _paq = window._paq || [];
  _paq.push(['trackPageView']);
  _paq.push(['enableLinkTracking']);
  (function() {
    var u="//{$PIWIK_URL}/";
    _paq.push(['setTrackerUrl', u+'piwik.php']);
    _paq.push(['setSiteId', {$IDSITE}]);
    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
    g.type='text/javascript'; g.async=true; g.defer=true; g.src=u+'piwik.js'; s.parentNode.insertBefore(g,s);
  })();
</script>
<!-- End Matomo Code -->

@rap-2-h 的回答很有效。为了在您的基本页面中包含脚本,您可以将 matomo 脚本作为 dangerouslySetInnerHTML 包含在 next.js <Head> 组件中,如下所示:

//import next had
import Head from 'next/head'

export default class Meta extends Component {

    render() {

        return (
          <Head>
            <script type="text/javascript" dangerouslySetInnerHTML={{
                    __html: ` var _paq = window._paq || [];
                    /* tracker methods like "setCustomDimension" should be called before "trackPageView" */
                    _paq.push(['trackPageView']);
                    _paq.push(['enableLinkTracking']);
                  (function () {
                        var u = "https://your_matomo_link";
                        _paq.push(['setTrackerUrl', u + 'matomo.php']);
                        _paq.push(['setSiteId', '1']);
                        var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0];
                        g.type = 'text/javascript'; g.async = true; g.defer = true; g.src = u + 'matomo.js'; s.parentNode.insertBefore(g, s);
                    })();
                `}} />

    </Head>
    )
   }
}

然后将其添加到布局的顶部或任何位置

我让它像这样工作

LayoutDefault.js

import NextHead from 'next/head'

export default function LayoutDefault() {
return (
    <div>
        <NextHead>
            …
            <script dangerouslySetInnerHTML={{ __html: `
                console.log('Matomo Component')

                var _paq = window._paq = window._paq || [];
                _paq.push(['trackPageView']);
                _paq.push(['enableLinkTracking']);
                (function() {
                    var u="{$MATOMO_URL}";
                    _paq.push(['setTrackerUrl', u+'matomo.php']);
                    _paq.push(['setSiteId', {$IDSITE}]);
                    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
                    g.type='text/javascript'; g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
                })();
            ` }} />
        </NextHead>
    </div>
)
}

_app.js

import { useEffect } from 'react'
import { useRouter } from 'next/router'

export default function MyApp({ Component, pageProps }) {
const router = useRouter()

useEffect(() => {
    const handleRouteChange = (url) => {
        if (window && window._paq) {
            _paq.push(['setCustomUrl', url]);
            _paq.push(['setDocumentTitle', document.title]);
            _paq.push(['trackPageView']);
        }
    }

    router.events.on('routeChangeStart', handleRouteChange)
}, [])

return <Component {...pageProps} />
}

在其他答案之上添加:您应该在 routeChangeStart 上使用 routeChangeComplete 事件以获得正确的数据 - 使用 routeChangeStart 您将获得上一页的页面 title/url。

完整的解决方案:

_app.js作为功能组件:

import { useRouter } from 'next/router'
import { useEffect } from 'react'

export default function App({ Component, pageProps }) {
    const router = useRouter()
    useEffect(() => {
        const handleRouteChange = (url) => {
            if (window && window._paq) {
                _paq.push(['setCustomUrl', url]);
                _paq.push(['setDocumentTitle', document.title]);
                _paq.push(['trackPageView']);
            }
        }

        router.events.on('routeChangeComplete', handleRouteChange)
    }, [])

    return (
        //your code
    )
}

layout.js:

import Head from 'next/head'

export default function Layout({ children }) {
    return (
        <>
            <Head>
                <script type="text/javascript" dangerouslySetInnerHTML={{__html: `
                    var _paq = window._paq = window._paq || [];
                    _paq.push(['trackPageView']);
                    _paq.push(['enableLinkTracking']);
                    (function() {
                    var u="//<YOUR_MATOMO_URL>";
                    _paq.push(['setTrackerUrl', u+'matomo.php']);
                    _paq.push(['setSiteId', '1']);
                    var d=document, g=d.createElement('script'), s=d.getElementsByTagName('script')[0];
                    g.async=true; g.src=u+'matomo.js'; s.parentNode.insertBefore(g,s);
                    })();
                `}} />
            </Head>
            //your code
        </>
    )
}

或者,您可以使用 next/script 中的脚本并将 js 包含在其中。