6

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

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

为了记录所有路线更改事件,我必须在我的应用程序中的哪里使用此代码?

“where”表示在哪个文件/类/方法中)

4

3 回答 3

7

您必须pages/_app.jscomponentDidMount方法中添加它:

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"]);
    }
  });
}

不要忘记在您的基本页面中初始化它(即您的布局或类似的东西):

<!-- 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 -->
于 2019-01-31T19:38:36.057 回答
0

@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>
    )
   }
}

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

于 2020-04-20T16:43:58.207 回答
0

我让它像这样工作

布局默认.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} />
}
于 2021-03-10T18:13:22.010 回答