Skip to content

Commit

Permalink
Update Google Analytics only_pageview mode to GA4 (#649)
Browse files Browse the repository at this point in the history
  • Loading branch information
maple3142 authored Nov 29, 2023
1 parent dedc827 commit 9bd24f7
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
2 changes: 2 additions & 0 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,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
Expand Down
32 changes: 25 additions & 7 deletions source/js/third-party/analytics/google-analytics.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down

0 comments on commit 9bd24f7

Please sign in to comment.