insert ads on HTML5 video

This is a quick off the cuff start of a solution that should at least point you in the right direction. This gives you a singleton with an init method that when called sets up a preroll on a particular video element.

var adManager = function () {
    var vid = document.getElementById("myVid"),
        adSrc = "videos/epic_rap_battles_of_history_16_adolf_hitler_vs_darth_vader_2_1280x720.mp4",
        src;

    var adEnded = function () {
        vid.removeEventListener("ended", adEnded, false);
        vid.src = src;
        vid.load();
        vid.play();
    };

    return {
        init: function () {
            src = vid.src;
            vid.src = adSrc;
            vid.load();
            vid.addEventListener("ended", adEnded, false);
        }
    };
}();

There are a number of things that aren't covered here, though. For instance, if you set the init method to be called when you start playing the video, you'll need to keep a flag that indicates whether there's an ad playing so that the play handler won't do anything when you're transitioning from the ad to the content (which requires a "play" event after the load() call in order to get the seamless playback).

We use something similar in our video playing project, and most of the video ad services out there do something like this for HTML based video playback (as opposed to Flash video playback).

It's relatively straightforward, but you just have to make sure to keep track of when event callbacks should be fired and when to add and remove those callbacks.

Another thing to consider is the unreliability of the "ended" event. I haven't yet figured out when and on which platforms it consistently fires, but it's a fairly well known problem. A possible solution is to use "timeupdate" instead and test whether the "currentTime" property is somewhere around a second less than the "duration" property so you know you're right at the end of the video.


Sorry I can't test this code right now but in theory this should work.

<script>
// you will want to do checking here to see if the browser supports the video element
document.getElementById('video').addEventListener('ended', function()
{
    // the ad finished playing so update the src attribute to the real video
    document.getElementById('video').src = 'mainvideo.webm';
});
</script>

<video id="video" src="ad.webm">
</video>

You may want to look at what Popcorn.js can do. It allows you to interact with Html5 video and overlay text and a lot of other cool things:

http://popcornjs.org/documentation

Tags:

Html

Video