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 also 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 works for tracking codes added using this method. If you are using a method provided by the theme, you may need to modify the theme files yourself, which is beyond the scope of this article.
Modification#
Let's paste the finished 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.mo") {
// 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 judgment before executing the code. If the current webpage's domain is blog.yfi.moe
, then the script for the analytics code will run; otherwise, it will not run.
I asked ChatGPT how to get the current domain, and it said to use the window.location.host
method. Then I 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's a bit strange, but it should work. Although I don't know if async
actually works, let's go with it.
Google provides two sections of code, and the second section is already JavaScript, so we can use it directly.
The same applies to the umami code.