Coder Social home page Coder Social logo

axllent / silverstripe-analytics-js Goto Github PK

View Code? Open in Web Editor NEW
16.0 4.0 4.0 92 KB

Extension to add Google Universal Analytics (gtag.js) tracking code to Silverstripe

License: MIT License

PHP 78.70% Scheme 21.30%
silverstripe php google-universal-analytics gtag google-analytics universal-analytics

silverstripe-analytics-js's Introduction

Google Universal Analytics for Silverstripe

An extension to add Google Universal Analytics gtag() tracking code (not to be confused with Google Tag Manager) to your Silverstripe templates.

It automatically includes optional unobtrusive event tracking for all outbound links & "asset downloads", as well as event tracking for 404 and error pages, email & telephone links.

Features

  • Google Universal Analytics (gtag.js) code injected automatically into <head> of page to prevent JavaScript conflicts due to loading order (if you are using custom gtag() functions in your other code.
  • Automatic pageview tracking for all configured accounts, including tracking of 404 & 500 page errors (tracked as "Page Not Found" / "Page Error" events).
  • Unobtrusive outbound, download, email & tel: link tracking - monitors all page clicks, rather than on page load (ie: works with links including those generated by Ajax etc on the page after page load).
  • Uses Google Analytics hitCallback for tracking for outgoing links to register before load (ie: when no link target is set) to ensure tracker is successfully run before redirection.
  • Tracking codes are automatically changed to UA-DEV-[1-9] if SS_ENVIRONMENT_TYPE is not live, or if page URL matches ?flush= to prevent bad data capture.

Event tracking

Additional event tracking is automatically enabled by default for:

  • File downloads (all non-image files in the assets folder) are tracked as "Downloads".
  • Outgoing links are tracked as "Outgoing Links".
  • Email (mailto:) links are tracked as "Email Links".
  • Phone (tel:) links are tracked as "Phone Links".

Event category names (eg: "Outgoing Links", "Downloads" etc) can be configured in your yaml config.

Note: Event tracking only works with regular (left-or-middle) mouse button clicks (including combinations with Ctrl/Shift/Meta keys). Tracking is bypassed if the user right-clicks on a link and selects an action from the context menu (open in new tab, save as etc...). Unfortunately there is no way around this without disabling the content menu entirely.

Requirements

  • Silverstripe ^4 || ^5

For the deprecated analytics.js tracking method for Silverstripe 4, please refer to the analytics.js branch.

For Silverstripe 3, please refer to the Silverstripe3 branch.

Installation via Composer

You can install it via composer with

composer require axllent/silverstripe-analytics-js

Basic usage

Once installed the extension is automatically loaded if you provide at least one tracking account in your config yaml file (eg) mysite/_config/analytics.yml

Axllent\AnalyticsJS\AnalyticsJS:
  tracker:
    - ['config', 'UA-1234567-1']

The syntax is very similar to the official documentation, so things like secondary trackers or other configurations can be easily added.

Axllent\AnalyticsJS\AnalyticsJS:
  tracker:
    - ['config', 'UA-1234567-1']          # default account [required]
    - ['config', 'UA-1234567-2']          # add secondary tracker
    - ['set', 'forceSSL', true]           # force tracking to use SSL
    - ['require', 'ecommerce', 'ecommerce.js']  # load ecommerce extension
  track_links: false                      # disable external link & asset tracking
  ignore_link_class:  "notrack"           # if "track_links", then ignore external links with the "notrack" class
  compress_js: false                      # do not compress inline JavaScript
  primary_gtag_id: "UA-1234567-1"         # set the default tracking id to be used when loading gtag (defaults to the first tracker)

Please refer to the Configuration.md for all configuration options.

To start live tracking, make sure your website is in live mode, or if running in dev or staging that you have the track_in_dev_mode: true option.

silverstripe-analytics-js's People

Contributors

axllent avatar jflearn avatar undefinedoffset avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

silverstripe-analytics-js's Issues

Problem when running the RebuildStaticCacheTask

When running the RebuildStaticCacheTask that is part of the silverstripe-staticpublisher, the $ga_trackers variable accumulates events in an unwanted fashion. The task builds for example the following set of pages:

FilesystemPublisher: Publishing to 
 * Publishing page 1/16: /silverstripe/
 * Publishing page 2/16: /silverstripe/de/
 * Publishing page 3/16: /silverstripe/de/about-us/
 * Publishing page 4/16: /silverstripe/de/contact-us/
 * Publishing page 5/16: /silverstripe/de/page-not-found/
 * Publishing page 6/16: /silverstripe/de/server-error/
 * Publishing page 7/16: /silverstripe/en/about-us/
 * Publishing page 8/16: /silverstripe/en/contact-us/
 * Publishing page 9/16: /silverstripe/en/page-not-found/
 * Publishing page 10/16: /silverstripe/en/server-error/
 * Publishing page 11/16: /silverstripe/fr/
 * Publishing page 12/16: /silverstripe/fr/about-us/
 * Publishing page 13/16: /silverstripe/fr/contact-us/
 * Publishing page 14/16: /silverstripe/fr/page-not-found/
 * Publishing page 15/16: /silverstripe/fr/server-error/

For the first page everything is ok and

ga("create","UA-DEV-1","auto");ga("send","pageview");

is inserted. The second page gets

ga("create","UA-DEV-1","auto");ga("send","pageview");ga("send","pageview");

the third

ga("create","UA-DEV-1","auto");ga("send","pageview");ga("send","pageview");ga("send","pageview")

Until finally

ga("create","UA-DEV-1","auto");ga("send","pageview");ga("send","pageview");ga("send","pageview");ga("send","pageview");ga("send","event","404 Page Not Found",document.location.pathname+document.location.search,document.referrer);ga("send","event","500 Page Error",document.location.pathname+document.location.search,document.referrer);ga("send","pageview");ga("send","pageview");ga("send","event","404 Page Not Found",document.location.pathname+document.location.search,document.referrer);ga("send","event","500 Page Error",document.location.pathname+document.location.search,document.referrer);ga("send","pageview");ga("send","pageview");ga("send","pageview");ga("send","event","404 Page Not Found",document.location.pathname+document.location.search,document.referrer);ga("send","event","500 Page Error",document.location.pathname+document.location.search,document.referrer);

is inserted into the last page.

[User Warning] when using in conjunction with Static Publishing

When running the RebuildStaticCacheTask that is part of https://github.com/silverstripe-labs/silverstripe-staticpublisher, the first page is published without error, but all subsequent throw a GaTracker::add_ga(): Default Tracker already set, please use name user warning.

Trace

trigger_error(GaTracker::add_ga(): Default Tracker already set, please use name,512)
AnalyticsJS.php:98

AnalyticsJS->parseGoogleUniversalAnalyticsConfigs()
AnalyticsJS.php:58

AnalyticsJS->injectGoogleUniversalAnalyticsCode()
AnalyticsJS.php:49

AnalyticsJS->onAfterInit(,,,,,,)
Object.php:998

Object->extend(onAfterInit)
Controller.php:145

Controller->handleRequest(SS_HTTPRequest,DataModel)
ContentController.php:197

ContentController->handleRequest(SS_HTTPRequest,DataModel)
ModelAsController.php:76

ModelAsController->handleRequest(SS_HTTPRequest,DataModel)
FluentRootURLController.php:97

FluentRootURLController->handleRequest(SS_HTTPRequest,DataModel)
Director.php:360

Director::handleRequest(SS_HTTPRequest,Session,DataModel)
Director.php:281

Director::test(http://localhost/~nbennett/neptun_web/de/)
FilesystemPublisher.php:231

FilesystemPublisher->publishPages(Array,,,,,,)
Object.php:998

Object->extend(publishPages,Array)
RebuildStaticCacheTask.php:107

RebuildStaticCacheTask->rebuildCache(Array,1)
RebuildStaticCacheTask.php:26

RebuildStaticCacheTask->run(SS_HTTPRequest)
TaskRunner.php:84

TaskRunner->runTask(SS_HTTPRequest)
RequestHandler.php:288

RequestHandler->handleAction(SS_HTTPRequest,runTask)
Controller.php:194

Controller->handleAction(SS_HTTPRequest,runTask)
RequestHandler.php:200

RequestHandler->handleRequest(SS_HTTPRequest,DataModel)
Controller.php:153

Controller->handleRequest(SS_HTTPRequest,DataModel)
RequestHandler.php:222

RequestHandler->handleRequest(SS_HTTPRequest,DataModel)
Controller.php:153

Controller->handleRequest(SS_HTTPRequest,DataModel)
Director.php:360

Director::handleRequest(SS_HTTPRequest,Session,DataModel)
Director.php:152

Director::direct(/dev/tasks/RebuildStaticCacheTask,DataModel)
main.php:189

require_once(/Users/nbennett/Sites/neptun_web/framework/main.php)
main.php:39

skipCache()
main.php:128

Despite the user warning, the resulting HTML is perfectly usable and Google Analytics seems to work fine.

The .js part of your module namespace might be problematic

Hey, just came across your module, very useful for the newer universal analytics however I have found that when you module is listed on the addons website the .js part causes some problems as I beleive it gets interpreted as a javascript file rather than a listing on the addons site.

Might pay to revise this and resubmit to packagist with a more meaningful name (perhaps include an indication that it is the universal tracking). For example: axllent/silverstripe-universalanalytics or something to that effect.

Moving to gtag.js

It looks like Google is starting to push users over to gtag.js instead of analytics.js, would you be open to a pull request to move this module over to it as well or would you rather we (WBG) fork the module and brand it as a new module under our org?

JS Code Displayed Twice

I'm running latest SS4 with the latest version of this module.

The JS code in both the head and body is being displayed twice as seen in the screenshot for the body code.

Screenshot 2023-10-25 at 9 28 21 AM

And just want to confirm the best way to setup the event for email and phone click tracking? I've only used this module with GA, new to GA4 and this module.

Screenshot 2023-11-08 at 12 40 30 PM

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.