How to insert Google Analytics after clicking a button?

夙愿已清 提交于 2019-12-11 09:33:27

问题


I'm trying to insert Google Analytics snippet after clicking a button, and therefore counting it as a visit.

Is it possible to do without needing to reload the page?


回答1:


You can use Event Tracking, namely trackPageView (found on David Walsh's site]:

_gaq.push(['_trackPageview', 'url-to-track.html']);

On a button:

var button = document.getElementsByTagName("button")[0];

button.addEventListener("click", function() {
  //Button click event
  alert("Tracking pageview");
  _gaq.push(['_trackPageview', 'url-to-track.html']);
}, false);
<button>Track me!</button>

In response to your comment:

var js = 'document.getElementsByTagName("button")[0].onclick=function(){alert("I\'m loaded!");}';

document.getElementsByTagName("button")[0].onclick = function() {
  var script = document.createElement("script");
  //Uncomment this and put the path for your file
  //script.src = "path/to/script.js";

  //Remove this, this is just for the demo
  script.innerHTML = js;

  document.body.appendChild(script);
  alert("Appended script, click the button again");
};
<button>Load a JS file</button>
<p>Or in this case, a string</p>



回答2:


First save the Analytics code into a variable.

Then append it to the head tag when the button is clicked.

ga = "(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){" +
     "(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o)," +
     "m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)" +
     "})(window,document,'script','//www.google-analytics.com/analytics.js','ga');" +
     "ga('create', 'UA-XXXXXXXX-X', 'auto');" +
     "ga('send', 'pageview');"

$('a.button').on('click', function() {
  $('head').append('<script>' + ga + '</script>');
});


来源:https://stackoverflow.com/questions/28590195/how-to-insert-google-analytics-after-clicking-a-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!