Handling Embedded Video and Proxies

I'm come across this problem quite regularly, but never think to write the steps down so have to think it all through every time! You've got a nice looking site and want to embed a video in it (say via YouTube). Unfortunately there's likely to be high footfall from those behind corporate proxies, and as a number of the embedded systems uses iframes, you end up with a nice error message slap in the middle of the page!

This documentation details a JS approach to handling this by hiding the iframe if the video doesn't load.

We could, create a proxy script that will effectively bypass some firewalls, but that's really not a good idea. At minimum you'll get blocked by a few businesses, or you may just find that you have astronomical bandwidth bills and high server load.

So instead we'll use JS to check whether or not the domain youtube.com is blocked. Sadly, a lot of browsers won't pass back an onerror event for iframes, so we need to do it another way.

So assuming we currently have the following in our markup



<iframe width="560" height="315" 
src="http://www.youtube.com/embed/fCIMYVOIokg" 
frameborder="0" allowfullscreen></iframe>



 

We need to add something from YouTube using something that does report back onerror. We can use an image for this, but its not always immediately obvious which one. Most of the images displayed are from Content Distribution Networks. The domain for the CDN may not have been blocked as administrators will often just block Youtube.com etc. But, one image that is always present is the Favicon. So we'll add favicon.ico



<iframe width="560" height="315" 
src="http://www.youtube.com/embed/fCIMYVOIokg" 
frameborder="0" allowfullscreen></iframe>
<img src="http://www.youtube.com/favicon.ico" 
style="width: 1px; height: 1px; display: hidden;">



 

We assign a small width and height as some browsers may not load the item if we use display none. Although the space will be occupied, it's only 1p x 1px so shouldn't be noticeable. Next we'll add some JS to finally do what we want (it really is this simple!)



<script type="text/javascript">

function youtube_borked(ele){
document.getElementById(ele).style.display = 'none';
</script>

<div id="YouTube1">
<iframe width="560" height="315" 
src="http://www.youtube.com/embed/fCIMYVOIokg" 
frameborder="0" allowfullscreen></iframe>

</div>
<img src="http://www.youtube.com/favicon.ico" 
style="width: 1px; height: 1px; display: hidden;" 
onerror="youtube_borked('YouTube1');">



 

It's a simplistic way of doing it, but it works. By calling a function, you've saved some typing if you need to call it more than once (put it in your sites main JS file). You could use a CSS class instead, but I've had problems with Internet Explorer in the past.