If you have enabled analytics code for your blog, the code will also run when testing locally, resulting in a large number of invalid localhost access records, which affects data accuracy. At the same time, I have a test domain that I don't want to trigger the analytics code when accessing.
So, how can I make the analytics code only run on my production domain blog.yfi.moe?
Prerequisite#
Injecting Analytics Code with Hexo
The method in this article only applies to tracking codes added using this method. If you are using a theme-provided method, you may need to modify the theme files yourself, which is beyond the scope of this article.
Modification#
Let's paste the final code:
After injecting this JavaScript code, it will only run on the current domain blog.yfi.moe
.
<script>
var host = window.location.host;
if (host == "blog.yfi.moe") {
// google analytics 1
(function () {
var ggtag = document.createElement('script');
ggtag.async = true;
ggtag.src = 'https://www.googletagmanager.com/gtag/js?id=G-*******'; // Modify the G- code here
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ggtag, s);
})();
//google analytics 2
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-********'); // Modify the G- code here
// umami
(function() {
var analytics = document.createElement('script');
analytics.async = true;
analytics.src = 'https://change-to-your.domain/script.js'; // Modify to your own domain
analytics.setAttribute('data-website-id', 'e0****a7-****-****-****-88e5****5132'); // Change to your tracking id
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(analytics, s);
})();
}
</script>
In simple terms, we need to make a condition before executing the code. If the current webpage's domain is blog.yfi.moe
, then run the analytics code script; otherwise, do not run it.
I asked ChatGPT how to get the current domain, and it said to use the window.location.host
method. I also asked how to convert <script async src="https://www.googletagmanager.com/gtag/js?id=G-*******"></script>
and similar scripts into pure JavaScript style. It said:
(function () {
var ggtag = document.createElement('script');
ggtag.async = true;
ggtag.src = 'https://www.googletagmanager.com/gtag/js?id=G-*******';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ggtag, s);
})();
It seems a bit strange, but it should work. Although I'm not sure if async
actually works, let's go with it.
Google provides two code snippets, and the second one is already JavaScript, so we can use it directly.
The same applies to the umami code.