5

I'm wondering how i can detect an 'audio' element that is not added to DOM before playing. The code that creates the element is:

var snd = new Audio("short.mp3");
snd.volume = 1;
snd.play();

The audio source may change.

Later i will inject some JS into the page using a chrome extension when the selected tab is audible. Then the code should run and do a console.log with the audio source.

How can i check stuff about this element that is never added to DOM?

PS: I can't change the code that plays the audio.

1 Answers1

4

Edit: Found this later: This answer by PhilHoy does exactly what mine does without adding another function to the Audio prototype. Wasn't familiar enough with apply when I wrote this, but the idea is the same.


Elaborating on Daniel Herr's comment:

You can overwrite the audio constructor

Looking around online for a bit, I couldn't find a better answer than this. You said, "...when the selected tab is audible. Then the code should run..." so I elected to overwrite the play method instead. Essentially, I'm just:

  • Saving a reference to the original play method
  • Replacing it with a function that logs
  • Calling the saved reference & passing along any arguments
  • Returning the result
Audio.prototype.overwrite_play = Audio.prototype.play

Audio.prototype.play = function() { 
  console.log(this.src)
  return this.overwrite_play(arguments); 
}

If you assigned play to an arbitrary variable, you would get the following error: 'play' called on an object that does not implement interface HTMLMediaElement.

So I elected to just add the method overwrite_play to the prototype of Audio itself. That gave me a this that referred to the particular Audio object anyway, so I could just use this.src directly. Only other catch is I'm pretty sure this only applies to audio sources created through new Audio & not embedded HTML audio elements.

There're probably much cleaner ways of dealing with this, but it seemed to work for one of my use-cases (adding a volume slider to specific tabs).

Lovethenakedgun
  • 731
  • 6
  • 22