Search code examples
javascripthtmlyoutube

Generate YouTube video's embed code using its URL


I want to add YouTube videos to my site. I want to know, is there a way to generate 'embed code' by giving the 'url'(that we input into the browser) as input?

In simpler words, is there a way to get 'embed code' as output by giving the 'url' of the video as input?

I read the YouTube's developer API docs. It talks about embedding the video but, I couldn't find anything regarding generation of the 'embed code' from the 'video's url'

I know I can manually copy the 'embed code' from the share link under YouTube's video. But I want to generate it using the 'video's url', removing the need of human effort in it.

Edit:

Some videos are blocked by YouTube. So, is there a way to show those videos on the site? If not, is there a way to at least detect whether it is 'blocked or not'?

For ex. - "http://www.youtube.com/watch?v=aOWB0yGTrNY&list=PLZnxqowr6IKiDvDkEfptk0lcXuJqzn_dN". This link when directly accessed through 'url' in an 'iframe' doesn't work. But if we go to this video on youtube and use its 'embed code url link' in an 'iframe', then it works. Please help me out with this.


Solution

  • Embed youtube video

    This creates the embed code... that you then have to append to the body.or wherever

    Function

    function yt(url){
    return '<iframe width="420" height="315" src="'+url+
    '" frameborder="0" allowfullscreen></iframe>'
    }
    

    Usage

    document.body.appendChild(document.createElement('div')).innerHTML=yt('yturl')
    

    if you have any questions just ask.

    this is prolly not the best solution but it's what you asked.

    EDIT

    Some videos are blocked from youtube/user and you can't simply add them to you page. btw all videos don't work inside other iframes.

    you can check the origin errors in your console.

    EDIT2

    Video is embeddable?

    You need to use the api to check for that

    http://gdata.youtube.com/feeds/api/videos?v=2&alt=json&q=Main%20Tera%20Hero%20-%20Official%20Trailer%20(HD)

    i think that what you are searching for is inside this tags

    yt$accessControl
    

    or

    app$control
    

    you can read more here

    https://stackoverflow.com/a/3937794/2450730

    &&

    http://apiblog.youtube.com/2011/12/understanding-playback-restrictions.html