JSFiddle - React, Tailwind, and code Playground

by Michael Prosser

HTML

<audio controls id="audioplayer_0"><source src="https://beyondwellsolutions.com/webmd/server/?file=../cdn/webm5ea0b28d9e8c7-beyondwellwebtopicsrev.mp3&amp;token=GADFDSJF^@*@#R(GD#@(DYGDADGASJDFGSAUY))" type="audio/mpeg"></audio>

JavaScript

var podcastTracker = function(audioElement){

  this.endpoint = 'https://beyondwellsolutions.com/webmd/ajax/track.php';

	this.call = function(action,player,podcast){
  
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = this.endpoint + '?action=' + action + '&player=' + player + '&podcast=' + podcast;
    
    document.getElementsByTagName('head')[0].appendChild(script);
    //console.log("calling script",script.src);
  
  }
  
  this.id = function () {
	  return '_' + Math.random().toString(36) + '.' + Math.random();
	};
  
  this.playerid = "webmd_api_" + this.id();
  this.podcast = audioElement.querySelectorAll('source')[0].src;
  
  this.updateStats = function(which){
  
  	this.call(which,this.playerid,this.podcast);
  
  }
  
  this.playerStarted = false;
  this.playerEnded = false;
  
  var cached_this = this;
  
  audioElement.onplaying = function() {
				
				if(!cached_this.playerStarted){
					
					cached_this.playerStarted = true;
					
         cached_this.updateStats('start');
					
				}
				
		};

	audioElement.onended = function() {
				
				if(!cached_this.playerEnded){
					
					cached_this.playerEnded = true;
					
					cached_this.updateStats('end');
					
				}
				
		};

}

// call once audio element exists passing the audio element into the tracker
// var tracker = new podcastTracker(document.getElementById('audioplayer_0'));

window.addEventListener('load', (event) => {
  var tracker = new podcastTracker(document.getElementById('audioplayer_0'));
});