diff --git a/_config.yml b/_config.yml index ab413a7db..e91561608 100644 --- a/_config.yml +++ b/_config.yml @@ -762,6 +762,8 @@ google_analytics: # By default, NexT will load an external gtag.js script on your site. # If you only need the pageview feature, set the following option to true to get a better performance. only_pageview: false + # only needed if you are using `only_pageview` mode, https://developers.google.com/analytics/devguides/collection/protocol/ga4 + measure_protocol_api_secret: # Baidu Analytics # See: https://tongji.baidu.com diff --git a/source/js/third-party/analytics/google-analytics.js b/source/js/third-party/analytics/google-analytics.js index 2cd128f76..8601806e0 100644 --- a/source/js/third-party/analytics/google-analytics.js +++ b/source/js/third-party/analytics/google-analytics.js @@ -22,13 +22,31 @@ if (!CONFIG.google_analytics.only_pageview) { if (CONFIG.hostname !== location.hostname) return; const uid = localStorage.getItem('uid') || (Math.random() + '.' + Math.random()); localStorage.setItem('uid', uid); - navigator.sendBeacon('https://www.google-analytics.com/collect', new URLSearchParams({ - v : 1, - tid: CONFIG.google_analytics.tracking_id, - cid: uid, - t : 'pageview', - dp : encodeURIComponent(location.pathname) - })); + fetch( + 'https://www.google-analytics.com/mp/collect?' + new URLSearchParams({ + api_secret : CONFIG.google_analytics.measure_protocol_api_secret, + measurement_id: CONFIG.google_analytics.tracking_id + }), + { + method : 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify({ + client_id: uid, + events : [ + { + name : 'page_view', + params: { + page_location: location.href, + page_title : document.title + } + } + ] + }), + mode: 'no-cors' + } + ); }; document.addEventListener('pjax:complete', sendPageView); sendPageView();