Programatically adding pageviews to Google Analytics

If you're not familiar with Google Analytics, then you're missing out on the best website user analysis software available.  Google provides it at no cost.  If you run AdWords campaigns or want to build sales funnels, this tool will compliment all of your hard work and help turn those visitors into conversions.  It will also provide valuable data about the technology of your visitors, which lets you tailor your experience to them.  

We are not going to touch on the setup of Google Analytics here.  We are going to look at sending extra pageviews to Google from end users on your site.

There are many reasons that would warrant sending an extra pageview to Google Analytics. The most common reason is that someone loaded more articles via an AJAX method or even used javascript to replace the content of a page with that of another.  On Single Page Applications (SPA) and mobile applications these are both commonplace.  Some industries even use it as a heartbeat if someone is sitting on a page for a while.  In the newspaper industry, a lot of big players send another impression every time they refresh ads or after a set interval, which I will sample below.

We are going to work using Google's modern implementation of gtag.js instead of analytics.js to keep with Google's recommendations.  If you haven't switched to using gtag, you're going to need to migrate first.

All of the following code should follow the including of Google's original code available through the Google Analytics administrative interface.

First things first, I'm going to show how to send a pageview.  The code allows you to customize the path, title and location.  If you don't customize them, it will use the current page information.  

That's very simple.  Every time you declare this, it sends a pageview.  What if you wanted to do it on a timer / interval?

There isn't a whole lot to it, but simple code can help keep your site statistics accurate.  Since there are many applications and variants in ways to apply the code, I am only able to cover a few basic examples.  If you have any questions, please comment or contact me.