From a9ee7dd0de0cce7b5a0f7c405e456fc6c7a2e1f1 Mon Sep 17 00:00:00 2001 From: Jeff Escalante Date: Wed, 15 Apr 2020 13:23:08 -0400 Subject: [PATCH] anchor link analytics (#7648) --- website/lib/anchor-link-analytics.js | 22 ++++++++++++++++++++++ website/pages/_app.js | 9 +++++++++ 2 files changed, 31 insertions(+) create mode 100644 website/lib/anchor-link-analytics.js diff --git a/website/lib/anchor-link-analytics.js b/website/lib/anchor-link-analytics.js new file mode 100644 index 0000000000..47b90c82f1 --- /dev/null +++ b/website/lib/anchor-link-analytics.js @@ -0,0 +1,22 @@ +// If there is a hash in the url, this script will check whether the hash matches +// the anchor link IDs for any element on the page and log it to our analytics. + +export default function anchorLinkAnalytics() { + if ( + typeof window === 'undefined' || + !window.requestIdleCallback || + !window.analytics + ) + return + + window.requestIdleCallback(() => { + const hash = window.location.hash + if (hash.length < 1) return + + const targets = [].slice.call( + document.querySelectorAll('.__target-lic, .__target-h') + ) + const targetMatch = targets.find((t) => t.id === hash.replace(/^#/, '')) + window.analytics.track('Anchor Link', { hash, hit: !!targetMatch }) + }) +} diff --git a/website/pages/_app.js b/website/pages/_app.js index d2d698a551..dc01cd80d3 100644 --- a/website/pages/_app.js +++ b/website/pages/_app.js @@ -11,6 +11,7 @@ import bugsnagClient from '../lib/bugsnag' import Error from './_error' import Head from 'next/head' import HashiHead from '@hashicorp/react-head' +import anchorLinkAnalytics from '../lib/anchor-link-analytics' Router.events.on('routeChangeStart', NProgress.start) Router.events.on('routeChangeError', NProgress.done) @@ -39,6 +40,14 @@ class NextApp extends App { return { pageProps } } + componentDidMount() { + anchorLinkAnalytics() + } + + componentDidUpdate() { + anchorLinkAnalytics() + } + render() { const { Component, pageProps } = this.props