141

I'm trying to put a YouTube video source into the HTML5 <video> tag, but it doesn't seem to work. After some Googling, I found out that HTML5 doesn't support YouTube video URLs as a source.

Can you use HTML5 to embed YouTube videos? If not, is there any workaround?

Simon East
  • 55,742
  • 17
  • 139
  • 133
sri
  • 3,319
  • 7
  • 34
  • 48
  • 2
    An IFrame solution as given below by http://stackoverflow.com/questions/5157377/show-youtube-video-source-into-html5-video-tag#answer-5345148 should suffice as a workaround. – S Meaden Mar 19 '17 at 13:34

8 Answers8

38

This answer does not work anymore, but I'm looking for a solution.

As of . 2015 / 02 / 24 . there is a website (youtubeinmp4) that allows you to download youtube videos in .mp4 format, you can exploit this (with some JavaScript) to get away with embedding youtube videos in <video> tags. Here is a demo of this in action.

##Pros

  • Fairly easy to implement.
  • Quite fast server response actually (it doesn't take that much to retrieve the videos).
  • Abstraction (the accepted solution, even if it worked properly, would only be applicable if you knew beforehand which videos you were going to play, this works for any user inputted url).

##Cons

  • It obviously depends on the youtubeinmp4.com servers and their way of providing a downloading link (which can be passed as a <video> source), so this answer may not be valid in the future.

  • You can't choose the video quality.


###JavaScript (after load)

videos = document.querySelectorAll("video");
for (var i = 0, l = videos.length; i < l; i++) {
    var video = videos[i];
    var src = video.src || (function () {
        var sources = video.querySelectorAll("source");
        for (var j = 0, sl = sources.length; j < sl; j++) {
            var source = sources[j];
            var type = source.type;
            var isMp4 = type.indexOf("mp4") != -1;
            if (isMp4) return source.src;
        }
        return null;
    })();
    if (src) {
        var isYoutube = src && src.match(/(?:youtu|youtube)(?:\.com|\.be)\/([\w\W]+)/i);
        if (isYoutube) {
            var id = isYoutube[1].match(/watch\?v=|[\w\W]+/gi);
            id = (id.length > 1) ? id.splice(1) : id;
            id = id.toString();
            var mp4url = "http://www.youtubeinmp4.com/redirect.php?video=";
            video.src = mp4url + id;
        }
    }
}

###Usage (Full)

<video controls="true">
        <source src="www.youtube.com/watch?v=3bGNuRtlqAQ" type="video/mp4" />
    </video>

Standard video format.

###Usage (Mini)

<video src="youtu.be/MLeIBFYY6UY" controls="true"></video>

A little less common but quite smaller, using the shortened url youtu.be as the src attribute directly in the <video> tag.

Ruslan López
  • 4,433
  • 2
  • 26
  • 37
undefined
  • 3,949
  • 4
  • 26
  • 38
28

The <video> tag is meant to load in a video of a supported format (which may differ by browser).

YouTube embed links are not just videos, they are typically webpages that contain logic to detect what your user supports and how they can play the youtube video, using HTML5, or flash, or some other plugin based on what is available on the users PC. This is why you are having a difficult time using the video tag with youtube videos.

YouTube does offer a developer API to embed a youtube video into your page.

I made a JSFiddle as a live example: http://jsfiddle.net/zub16fgt/

And you can read more about the YouTube API here: https://developers.google.com/youtube/iframe_api_reference#Getting_Started

The Code can also be found below

In your HTML:

<div id="player"></div>

In your Javascript:

var onPlayerReady = function(event) {
    event.target.playVideo();  
};

// The first argument of YT.Player is an HTML element ID. 
// YouTube API will replace my <div id="player"> tag 
// with an iframe containing the youtube video.

var player = new YT.Player('player', {
    height: 320,
    width: 400,
    videoId : '6Dc1C77nra4',
    events : {
        'onReady' : onPlayerReady
    }
});
Norman Breau
  • 2,132
  • 16
  • 35
  • I recently got this problem: The fullscreen is no longer supported on iPad! Your jsfiddle-example are perfect to illustrate: On pc it works, on iPad not. ..I guess I should ask a new question on this, but someone here maybe can comment? – Tornseglare Apr 04 '18 at 11:09
  • 1
    @Snorvarg My answer should works on any HTML5 compliant browser, which as long as you're running a rather recent version version of iOS (10+) on your iPad it should work. If you don't need to programmatically control the video, you can try using the simple iframe embed API. You can find an example here https://developers.google.com/youtube/iframe_api_reference#Examples, or view vinayvasyani's answer. If you still have a problem, then I would ask a new question using the "How to Ask a Good Question" guidelines found at https://stackoverflow.com/help/how-to-ask. – Norman Breau Apr 05 '18 at 13:38
  • @Snorvarg I came across this https://productforums.google.com/forum/#!topic/youtube/q7cAnPlN_-Y, a similar issue occuring in Firefox and it was resolved because they needed to request full screen permissions. So I'm willing to bet that's why full screen isn't working on your iPad, which unfortunately iOS Safari doesn't appear to support. An alternate solution is to add your own full screen button and just resize the iframe player to the width/height of your screen. – Norman Breau Apr 05 '18 at 13:59
  • 1
    Thanks for your tips and links. I added a question a few days ago, here: https://stackoverflow.com/questions/49650040/fullscreen-button-in-embedded-youtube-player-disabled-on-ipad But after a while, I decided to make a fullscreen button of my own as you have proposed, and it works fine. – Tornseglare Apr 09 '18 at 16:10
  • 2
    Great stuff, however I ran into the error "TypeError: YT.Player is not a constructor", as described here: https://stackoverflow.com/questions/52062169/uncaught-typeerror-yt-player-is-not-a-constructor. As the (only) answer points out, this results of the asynchronous script load and the API not yet being ready when being called. This can be avoided by implementing the `onYouTubeIframeAPIReady` function (and putting the last code block of above code inside it). – jakob.j Feb 24 '20 at 19:54
28

I have created a realtively small (4.89 KB) javascript library for this exact functionality.

Found on my GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/

It's as simple as:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader@2.0.0/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

Working example here: https://jsfiddle.net/thelevicole/5g6dbpx3/1/

What the library does is extract the video ID from the data attribute and makes a request to the https://www.youtube.com/get_video_info?video_id=. It decodes the response which includes streaming information we can use to add a source to the <video> tag.


UPDATE June 2021

YouTube have recently updated their API which has broken previous versions of this package. Please now use versions 4.0.1 and up! Updated example:

<video data-yt2html5="https://www.youtube.com/watch?v=ScMzIvxBSi4"></video>

<script src="https://cdn.jsdelivr.net/gh/thelevicole/youtube-to-html5-loader@4.0.1/dist/YouTubeToHtml5.js"></script>
<script>new YouTubeToHtml5();</script>

https://jsfiddle.net/thelevicole/5g6dbpx3/2/

Levi Cole
  • 3,561
  • 1
  • 21
  • 36
  • 2
    Could you please explain how to set it up in Angular? – Toto Briac Jan 08 '21 at 08:44
  • Hi @levi-cole I tried your GitHub code , but is showing me this error : https://prnt.sc/107j0as – Parthavi Patel Feb 26 '21 at 10:49
  • @ParthaviPatel please can you open an issue on GitHub here: https://github.com/thelevicole/youtube-to-html5-loader/issues thanks! – Levi Cole Mar 05 '21 at 14:45
  • 2
    It should be mentioned somewhere that this library makes requests to the author's server, yt2html.com in order to retrieve the video streaming src. – Spankied Aug 23 '21 at 23:57
  • 1
    @Spankied correct! Versions prior to 4.0.1 were able to contact YouTubes API directly but they then implemented CORS headers preventing the data to be retrieved via Ajax. My server, however, can still successfully make the request so it acts as a very basic middle man. – Levi Cole Aug 24 '21 at 08:35
  • @LeviCole Is the server open source, or just the npm package? – Matt Huggins Feb 06 '22 at 19:15
  • i was using this yesterday and it was working but now it doesnt and i think its because YouTube wants us to use the Iframe API: https://developers.google.com/youtube/iframe_api_reference – jsky Jun 12 '22 at 10:08
  • TypeError: Cannot read properties of undefined (reading 'streamingData') at YouTubeToHtml5.parseYoutubeMeta (YouTubeToHtml5.js:1:4584) at YouTubeToHtml5.js:1:6023 YouTubeToHtml5.parseYoutubeMeta @ YouTubeToHtml5.js:1 (anonymous) @ YouTubeToHtml5.js:1 XMLHttpRequest.send (async) (anonymous) @ YouTubeToHtml5.js:1 YouTubeToHtml5.fetch @ YouTubeToHtml5.js:1 YouTubeToHtml5.loadSingle @ YouTubeToHtml5.js:1 (anonymous) @ YouTubeToHtml5.js:1 YouTubeToHtml5.load @ YouTubeToHtml5.js:1 YouTubeToHtml5 @ YouTubeToHtml5.js:1 (anonymous) @ ?editor_console=true:112 – Per Quested Aronsson Apr 21 '23 at 07:58
15

Step 1: add &html5=True to your favorite youtube url

Step 2: Find <video/> tag in source

Step 3: Add controls="controls" to video tag: <video controls="controls"..../>

Example:

<video controls="controls" class="video-stream" x-webkit-airplay="allow" data-youtube-id="N9oxmRT2YWw" src="http://v20.lscache8.c.youtube.com/videoplayback?sparams=id%2Cexpire%2Cip%2Cipbits%2Citag%2Cratebypass%2Coc%3AU0hPRVRMVV9FSkNOOV9MRllD&amp;itag=43&amp;ipbits=0&amp;signature=D2BCBE2F115E68C5FF97673F1D797F3C3E3BFB99.59252109C7D2B995A8D51A461FF9A6264879948E&amp;sver=3&amp;ratebypass=yes&amp;expire=1300417200&amp;key=yt1&amp;ip=0.0.0.0&amp;id=37da319914f6616c"></video>

Note there seems to some expire stuff. I don't know how long the src string will work.

Still testing myself.

Edit (July 28, 2011): Note that this video src is specific to the browser you use to retrieve the page source. I think Youtube generates this HTML dynamically (at least currently) so in testing if I copy in Firefox this works in Firefox, but not Chrome, for example.

Ruslan López
  • 4,433
  • 2
  • 26
  • 37
Simon Flack
  • 486
  • 3
  • 3
  • 106
    The expiration and fact that it only works in a specific browser makes this solution pretty useless. – pjv Nov 05 '11 at 21:04
  • 1
    Is it capable of playing ALL youtube videos? – Raj Pawan Gumdal Jun 11 '12 at 06:27
  • 3
    YouTube could theoretically change the underlying storage URLs for all of their videos if they'd like at any time. The URL provided in the `src` attribute above is probably not guaranteed to work long-term. – Chris Peters Sep 05 '13 at 10:41
  • 2
    Yes, useful information but sounds like a bad idea. YouTube could decide to close access to the direct video link at any time. – Oliver Moran Dec 11 '13 at 10:12
-4

how about doing it the way hooktube does it? they don't actually use the video URL for the html5 element, but the google video redirector url that calls upon that video. check out here's how they present some despacito random video...

<video id="player-obj" controls="" src="https://redirector.googlevideo.com/videoplayback?ratebypass=yes&amp;mt=1510077993----SKIPPED----amp;utmg=ytap1,,hd720"><source>Your browser does not support HTML5 video.</video>

the code is for the following video page https://hooktube.com/watch?v=72UO0v5ESUo

youtube to mp3 on the other hand has turned into extremely monetized monster that returns now download.html on half of video download requests... annoying...

the 2 links in this answer are to my personal experiences with both resources. how hooktube is nice and fresh and actually helps avoid censorship and geo restrictions.. check it out, it's pretty cool. and youtubeinmp4 is a popup monster now known as ConvertInMp4...

-4

In case anyone stumbles upon this question, a neat way to embed YouTube video is to use embed tag, like so: <embed src="https://www.youtube-nocookie.com/embed/DelkRGZCtTs" width="100%" height="333">

Mateusz
  • 454
  • 4
  • 13
-6

The easiest answer is given by W3schools. https://www.w3schools.com/html/html_youtube.asp

  1. Upload your video to Youtube
  2. Note the Video ID
  3. Now write this code in your HTML5.
<iframe width="640" height="520"
src="https://www.youtube.com/embed/<VideoID>">
</iframe>
-12

With the new iframe tag embedded in your website, the code will automatically detect whether you are using a browser that supports HTML5 or not.

The iframe code for embedding YouTube videos is as follows, simply copy the Video ID and replace in the code below:

<iframe type="text/html" 
    width="640" 
    height="385" 
    src="http://www.youtube.com/embed/VIDEO_ID"
    frameborder="0">
</iframe>
Zearin
  • 1,474
  • 2
  • 17
  • 36
vinayvasyani
  • 1,393
  • 4
  • 13
  • 34
  • 31
    "New" `iframe` tag? `iframe` has been around for ages… – Zearin Dec 11 '13 at 18:38
  • 15
    This is not a solution to the answer, it clearly states video tag and not iframe... – TGarrett Aug 13 '15 at 18:45
  • 9
    Maybe the OP just didn't know about the existence of the `iframe` tag and that's why he directly asked about the `video` tag. Otherwise he wouldn't have asked if HTML5 (generically) supports Youtube videos, but he would have restricted the question to the `video` tag. He even asked "is there any workaround for that?" in his last sentence, so this answer is perfectly valid. – Daniel Muñoz Parsapoormoghadam Oct 15 '15 at 12:24
  • 1
    To embed youtube.com videos in my blogger.com blog, iframe is the only convenient solution. On top of that, the embed code that youtube.com generates is an iframe tag. Also, w3schools.com recommends iframes: [http://www.w3schools.com/html/html_youtube.asp](http://www.w3schools.com/html/html_youtube.asp). Where the video tag is not mentioned. – noobninja May 16 '16 at 19:25
  • 1
    Just in case if anyone is curious... The issue is using a video tag is not the proper approach for YouTube videos because the public URLs to embed YouTube videos aren't an actual media resource. That is why there are people suggesting using iframes. Trying to use a video tag will mean you will be using private URLs that may change in the future. It is like attempting to access a private member in an object-oriented language. You can view YouTube's official documentation here https://developers.google.com/youtube/iframe_api_reference#Examples – Norman Breau Apr 05 '18 at 13:46