This is a sample how to implement Google Analytics in static web site without authenticating of users.
There are components.
-
show_pageviews.html - shows pageviews counter.
-
pageviews.js - access to Google Analytics.
-
report_access.js - token to authorize access to Google Analytics.
-
generate_token.py - a tool to generate Google Analytics token.
-
[key name].json - Google analytics service account key file created in Google Analytics Platform APIs and Services.
usage: generate_token.py [-h] -k KEYFILEPATH -t TOKENFILEPATH
Generate Google Analytics token v. 1.0.0
optional arguments:
-h, --help show this help message and exit
-k KEYFILEPATH, --keyfilepath KEYFILEPATH
Google Analytics json key file path
-t TOKENFILEPATH, --tokenfilepath TOKENFILEPATH
Google Analytics token destination path
Sample of usage in CentOS 8 where the tool and service account file located in /opt/generate_token
folder and web site in /var/www/sample.com
folder
python3 /opt/generate_token/generate_token.py -k /opt/generate_token/tech-jogging-blog-98stj21aac52.json -t /var/www/sample.com/report_access.js
- Install Pyhon library
sudo pip3 install oauth2client
- Generate a token. It's live for 1 hour.
- Publish 3 files to a web server.
- how_pageviews.html
- pageviews.js
- report_access.js
- Open show_pageviews.html page.
- If you need to keep it running, renew the token every hour.
- Switch to root account.
sudo su
- Open
crontab
editor.
crontab -e
- Add the command item.
59 * * * * python3 /opt/generate_token/generate_token.py -k /opt/generate_token/tech-jogging-blog-98stj21aac52.json -t /var/www/sample.com/report_access.js
It can be optimized by creating a shell script file, for example, launcher.sh
and placing the command in the shell file. In that case, the command item is.
59 * * * * python3 /opt/generate_token/launcher.sh
- Validate your setup.
crontab -l