Skip to content

Instantly share code, notes, and snippets.

@watab0shi
Last active October 4, 2021 03:13
Show Gist options
  • Select an option

  • Save watab0shi/c10fd8d4f8a987d0244d9c2b777c8bb8 to your computer and use it in GitHub Desktop.

Select an option

Save watab0shi/c10fd8d4f8a987d0244d9c2b777c8bb8 to your computer and use it in GitHub Desktop.
自作SPAでGAのページビューを発火
let isGACreated = false;
window.addEventListener('hashchange', () => {
const hash = location.hash.length > 0 ? location.hash.slice(1) : 'index';// '#' を削除, 空だったら index にする
if (typeof window.ga === 'function') {
if (!isGACreated) {// 初回のみ create する
ga('create', 'UA-XXXXXXXXX', 'auto');
isGACreated = true;
}
const pathname = location.pathname.slice(0, location.pathname.lastIndexOf('/') + 1);// ファイル名ついてたら削除
const virtualPath = `${ pathname + hash }.html`;
ga('send', 'pageview', { 'page': virtualPath, 'title': hash });
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment