slinkhi slinkhi - 3 months ago 10
Javascript Question

capturing video source on html5 video play event

My goal is to get the

src
of the video playing, when the video is played.

I currently have the following code:

<!doctype html>
<html>
<head>
</head>
<body>
<video width="320" height="240" controls>
<source src="video.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

<script type='text/javascript'>
var vid = document.getElementsByTagName('video')[0];
vid.addEventListener('play', function() {
console.log('video source:',this.src);
}, false);
</script>
</body>
</html>


So my first problem is that
this.src
doesn't work; it outputs an empty string. I assume this is because the
src
isn't actually part of the
video
tag, but is in the
source
child tag.

I then tried to add into my function the following:

for (var p in this) {
console.log(p, this[p]);
}


I did this to see if I could find any properties referencing it.. but I don't see anything that directly references it? So is the only way to get the source really to grab the child
source
nodes? If so... then...

My 2nd question, how would I determine which
src
attribute is actually being used to play the video? IOW if
video.mp4
was actually used to play the video, I want to know that value, but if
video.ogg
was actually used to play the video, I want to know that value instead.

Answer

You can try this way:

var vid = document.getElementsByTagName('video')[0];

vid.addEventListener('play', function() {
    console.log('video source:',this.currentSrc);
}, false);