22
33import { useEffect } from 'react' ;
44import Script from 'next/script' ;
5- import { usePathname , useSearchParams } from 'next/navigation' ;
65
76declare global {
87 interface Window {
@@ -11,9 +10,6 @@ declare global {
1110}
1211
1312export function Analytics ( ) {
14- const pathname = usePathname ( ) ;
15- const searchParams = useSearchParams ( ) ;
16-
1713 useEffect ( ( ) => {
1814 if ( typeof window !== 'undefined' ) {
1915 const terminationEvent = 'onpagehide' in window ? 'pagehide' : 'unload' ;
@@ -30,15 +26,23 @@ export function Analytics() {
3026 } , [ ] ) ;
3127
3228 useEffect ( ( ) => {
33- if ( pathname && window . gtag ) {
34- const cleanedUrl = `${ pathname } ${
35- searchParams ?. toString ( ) ? `?${ searchParams . toString ( ) } ` : ''
36- } `. split ( / [ \? \# ] / ) [ 0 ] ;
37- window . gtag ( 'event' , 'pageview' , {
38- event_label : cleanedUrl ,
39- } ) ;
40- }
41- } , [ pathname , searchParams ] ) ;
29+ // If only we had router events. But patching pushState is what Vercel Analytics does.
30+ // https://va.vercel-scripts.com/v1/script.debug.js
31+ const originalPushState = history . pushState ;
32+
33+ history . pushState = function ( ...args ) {
34+ const oldCleanedUrl = window . location . href . split ( / [ \? \# ] / ) [ 0 ] ;
35+ originalPushState . apply ( history , args ) ;
36+ const newCleanedUrl = window . location . href . split ( / [ \? \# ] / ) [ 0 ] ;
37+ if ( oldCleanedUrl !== newCleanedUrl ) {
38+ window ?. gtag ( 'set' , 'page' , newCleanedUrl ) ;
39+ window ?. gtag ( 'send' , 'pageview' ) ;
40+ }
41+ } ;
42+ return ( ) => {
43+ history . pushState = originalPushState ;
44+ } ;
45+ } , [ ] ) ;
4246
4347 return (
4448 < >
0 commit comments