2019-03-01 update: The bug on the navigatedEvent seems to be fixed now, so I have updated the code below. I have also sent a PR with the changes to the original repository (by João Ferreira) where you can get a full project.
I’ve been asked by a client to help them add Google Analytics to a modern SharePoint site in order to track all page views.
The first thing that came to my mind was to look for a solution available online as this is a fairly common scenario, which was also what the client tried to do and got stuck with some limitations on the solutions that they have found.
There are plenty of solutions available online, from complete implementations to blog posts with the relevant code snippets, but I was also unable to find one that was able to track full and partial page loads, so I decided to tweak one to work on the required scenarios.
The code below is based on the original solution provided by João Ferreira on this blog post where he uses a SPFx application customizer to load the script on every SharePoint page. When testing it, we found that it was not tracking all the page loads that we required, so we updated it slightly.
Additionally, the this.context.application.navigatedEvent event currently has a known bug and fires twice. The workaround provided by jonthenerd worked fine in this scenario.
Regarding tracking of pages that are only loaded partially, the code below simply uses the approach provided by Google for tracking Single Page Applications.
Hope you fins this useful, and feel free to leave comments or provide feedback.