mercredi 30 décembre 2020

execute javascript pixel from separate file

I have the following sudo javascript code I wish to call when a user visits a page of my website (adapted from https://cloud.google.com/recommendations-ai/docs/record-events#monitor):

<script type="text/javascript">
var user_event = {
  "eventType" : "detail-page-view",
};

var _gre = _gre || [];
_gre.push(['apiKey', '<MY API KEY>']);
_gre.push(['logEvent', user_event]);

(function() {
  var gre = document.createElement('script'); gre.type = 'text/javascript'; gre.async = true;
  gre.src = 'https://www.gstatic.com/recommendationengine/v1beta_event.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gre, s);
})();

</script>

The script runs successfully, however, I want to organize my javascript into a separate file.

I have created assets/custom.js and loaded the functions successfully. I then call the function like this from the same page:

<script type="text/javascript">
  detailPageView();
</script>

and in assets/custom.js I have:

function detailPageView(){
  // exact same code as above!
  var user_event = {
  "eventType" : "detail-page-view",
};

var _gre = _gre || [];
_gre.push(['apiKey', '<MY API KEY>']);
_gre.push(['logEvent', user_event]);

(function() {
  var gre = document.createElement('script'); gre.type = 'text/javascript'; gre.async = true;
  gre.src = 'https://www.gstatic.com/recommendationengine/v1beta_event.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gre, s);
})();
}

I code runs, however, the script does not successfully log the event. How can I fix this?




Aucun commentaire:

Enregistrer un commentaire