Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Google Analytics only_pageview mode to GA4 #649

Merged
merged 1 commit into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
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,

Check warning

Code scanning / CodeQL

Client-side cross-site scripting (experimental)

(Experimental) This may be a cross-site scripting vulnerability due to [a user-provided value](1). Identified using machine learning.
page_title : document.title
}
}
]
}),
mode: 'no-cors'
}
);
};
document.addEventListener('pjax:complete', sendPageView);
sendPageView();
Expand Down
Loading