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).