SharePoint – How To: Dynamically convert youtube URLs into embed videos

Ok, so the scenario is simple. You have a SharePoint page, a WIKI, a Blog, or a publishing page and you decided to add YouTube video links to it. Links are great, but you want to display embeds. You probably don’t want your users messing with the HTML to try getting the embed code right. Not only that, but on many SharePoint site templates, say blog template, SharePoint automatically strips any script tags from the post.

The easiest solution is to use jQuery in your masterpage which will parse all links according to a regular expression and convert YouTube links to embeds.

Here is how to do it quickly in SharePoint designer:
1. Open your site in SharePoint designer and get to the masterpage
2. Add the following code in to the <head> section of the page:


< script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
< script language="javascript" type="text/javascript">
$(document).ready(function(){
$('a').each(function() {

var yturl= /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([\w\-]{10,12})(?:&feature=related)?(?:[\w\-]{0})?/g;
var ytplayer= ‘‘;

var url = $(this).attr(‘href’);
if (url != null)
{
var matches = url.match(yturl);
if (matches)
{
var embed = $(this).attr(‘href’).replace(yturl, ytplayer);
var iframe = $(embed);

iframe.insertAfter(this);
$(this).remove();
}
}
});
});
< /script>

If you like to change the dimensions of the embed, you can do so in the ytplayer variable above.

One thought on “SharePoint – How To: Dynamically convert youtube URLs into embed videos

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: