Friday, May 22, 2009

Embedding YouTube Videos on Secure Web Sites.

Currently YouTube doesn't offer an option of embedding its videos via https, so if you try to add a video to a secure page browsers will display a security warning. If you use swfobject.js instead of the code provided by YouTube (as you should!), you'll find the security warning goes away ... in some browsers; IE is fooled and doesn't display a warning, while FireFox will still show its little red exclamation mark in the status bar indicating that not all elements on the page are secure:



The same issue occurs in Opera, as well as Flock and other Mozilla browsers.


And obviously, since swfobject is a JavaScript file, if JavaScript is disabled in the browser the only option for showing the video is a plain ol' Flash object inside noscript tags, and in that case the security warning is displayed for all browsers.


The workaround I came up with is to upload a SWF to the secure site that acts as a proxy and loads the YouTube video (since Flash has its own security model, it doesn't matter that the video is not served via https).


Here is an example from peta2's "Whose Skin Are You In?" Web site:


peta2's "Whose Skin Are You In" video


I've posted the SWF I created to Google Code at http://code.google.com/p/ytplayer.


Here's the ActionScript that makes it all work:


Stage.align="TL";

Stage.scaleMode="noscale";


System.security.allowDomain("http://www.youtube.com");

System.security.loadPolicyFile("http://www.youtube.com/crossdomain.xml");


//create a MovieClip to load the player into

ytplayer=createEmptyMovieClip("ytplayer",1);


//create a listener object for the MovieClipLoader to use

ytPlayerLoaderListener={};

var loadInterval:Number;


//When the player clip first loads, we start an interval to check for when the player is ready

ytPlayerLoaderListener.onLoadInit=function(){

   loadInterval=setInterval(checkPlayerLoaded,250);

}

function checkPlayerLoaded():Void{

   //once the player is ready, we can subscribe to events

   if(ytplayer.isPlayerLoaded()){

      ytplayer.setSize(Stage.width,Stage.height);

      clearInterval(loadInterval);

   }

}


//create a MovieClipLoader to handle the loading of the player

ytPlayerLoader=new MovieClipLoader();

ytPlayerLoader.addListener(ytPlayerLoaderListener);


//load the player

ytPlayerLoader.loadClip("http://www.youtube.com/v/"+vidId+"&hl=en&fs=1",ytplayer);


//adjust size when user clicks full-screen

var listener:Object=new Object();

Stage.addListener(listener);

listener.onFullScreen=respondFunction;

function respondFunction(){

   ytplayer.setSize(Stage.width,Stage.height);

}