[javascript] How to embed an autoplaying YouTube video in an iframe?

I am trying to embed the new iframe version of a YouTube video and get it to auto play.

As far as I can tell, there is no way of doing this by amending flags to the URL. Is there a way to do it by using JavaScript & the API?

This question is related to javascript html iframe youtube youtube-api

The answer is


The embedded code of youtube has autoplay off by default. Simply add autoplay=1at the end of "src" attribute. For example:

<iframe src="http://www.youtube.com/embed/xzvScRnF6MU?autoplay=1" width="960" height="447" frameborder="0" allowfullscreen></iframe>

Since April 2018, Google made some changes to the Autoplay Policy. You not only need to add the autoplay=1 as a query param, but also add allow='autoplay' as an iframe's attribute

So you will have to do something like this:

<iframe src="https://www.youtube.com/embed/VIDEO_ID?autoplay=1" allow='autoplay'></iframe>

To have the accepted answer by mjhm working on Chrome 66 in May 2018, I added allow=autoplay to the iframe and enable_js=1 to the query string:

<iframe allow=autoplay width="420px" height="345px" src="http://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&enable_js=1"></iframe>

Multiple queries tip for those who don't know (past me and future me)

If you're making a single query with the url just ?autoplay=1 works as shown by mjhm's answer

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1"></iframe>

If you're making multiple queries remember the first one begins with a ? while the rest begin with a &

Say you want to turn off related videos but enable autoplay...

This works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0&autoplay=1"></iframe>

and this works

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?autoplay=1&rel=0"></iframe>

But these won't work..

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0?rel=0?autoplay=1"></iframe>

<iframe src="https://www.youtube.com/embed/oHg5SJYRHA0&autoplay=1&rel=0"></iframe>

example comparisons

https://jsfiddle.net/Hastig/p4dpo5y4/

more info

Read NextLocal's reply below for more info about using multiple query strings


December 2018,

Looking for an AUTOPLAY, LOOP, MUTE youtube video for react.

Other answers didn't worked.

I found a solution with a library: react-youtube

class Video extends Component {

    _onReady(event) {
        // add mute
        event.target.mute();
        // add autoplay
        event.target.playVideo();
    }

    render() {
        const opts = {
            width: '100%',
            height: '700px',
            playerVars: {
                // remove video controls 
                controls: 0,
                // remove related video
                rel: 0
            }
        };

        return (
            <YouTube
                videoId="oHg5SJYRHA0"
                opts={opts}
                // add autoplay
                onReady={this._onReady}
                // add loop
                onEnd={this._onReady}
            />
        )
    }

}

<iframe width="560" height="315" 
        src="https://www.youtube.com/embed/9IILMHo4RCQ?rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1" 
        frameborder="0" allowfullscreen></iframe>

at the end of the iframe src, add &enablejsapi=1 to allow the js API to be used on the video

and then with jquery:

jQuery(document).ready(function( $ ) {
  $('.video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
});

this should play the video automatically on document.ready

note, that you could also use this inside a click function to click on another element to start the video

More importantly, you cannot auto-start videos on a mobile device so users will always have to click on the video-player itself to start the video

Edit: I'm actually not 100% sure on document.ready the iframe will be ready, because YouTube could still be loading the video. I'm actually using this function inside a click function:

$('.video-container').on('click', function(){
  $('video-selector iframe')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');
  // add other code here to swap a custom image, etc
});

Nowadays I include a new attribute "allow" on iframe tag, for example:

allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"

The final code is:

<iframe src="https://www.youtube.com/embed/[VIDEO-CODE]?autoplay=1" 
frameborder="0" style="width: 100%; height: 100%;"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"></iframe>

2014 iframe embed on how to embed a youtube video with autoplay and no suggested videos at end of clip

rel=0&amp;autoplay 

Example Below: .

<iframe width="640" height="360" src="//www.youtube.com/embed/JWgp7Ny3bOo?rel=0&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

1 - add &enablejsapi=1 to IFRAME SRC

2 - jQuery func:

  $('iframe#your_video')[0].contentWindow.postMessage('{"event":"command","func":"playVideo","args":""}', '*');

Works fine


To use javascript api,

<script type="text/javascript" src="swfobject.js"></script>
  <div id="ytapiplayer">
    You need Flash player 8+ and JavaScript enabled to view this video.
  </div>

  <script type="text/javascript">

    var params = { allowScriptAccess: "always" };
    var atts = { id: "myytplayer" };
    swfobject.embedSWF("http://www.youtube.com/v/OyHoZhLdgYw?enablejsapi=1&playerapiid=ytplayer&version=3",
                       "ytapiplayer", "425", "356", "8", null, null, params, atts);

  </script>

To play the youtube with the id:

swfobject.embedSWF

reference: https://developers.google.com/youtube/js_api_referencemagazine


The flags, or parameters that you can use with IFRAME and OBJECT embeds are documented here; the details about which parameter works with what player are also clearly mentioned:

YouTube Embedded Players and Player Parameters

You will notice that autoplay is supported by all players (AS3, AS2 and HTML5).


August 2018 I didn't find a working example on the iframe implementation. Other questions were related to Chrome only, which gave it away a little.

You'll have to mute sound mute=1 in order to autoplay on Chrome. FF and IE seem to be working just fine using autoplay=1 as parameter.

<iframe src="//www.youtube.com/embed/{{YOUTUBE-ID}}?autoplay=1&mute=1" name="youtube embed" allow="autoplay; encrypted-media" allowfullscreen></iframe>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to iframe

Getting all files in directory with ajax YouTube Autoplay not working Inserting the iframe into react component How to disable auto-play for local video in iframe iframe refuses to display iFrame onload JavaScript event YouTube iframe embed - full screen Change New Google Recaptcha (v2) Width load iframe in bootstrap modal Responsive iframe using Bootstrap

Examples related to youtube

Youtube - downloading a playlist - youtube-dl YouTube Autoplay not working How to embed new Youtube's live video permanent URL? How do you use youtube-dl to download live streams (that are live)? How can I get the actual video URL of a YouTube live stream? YouTube: How to present embed video with sound muted ffprobe or avprobe not found. Please install one Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 cast_sender.js error: Failed to load resource: net::ERR_FAILED in Chrome Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Examples related to youtube-api

How can I get the actual video URL of a YouTube live stream? Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000 Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN' Google OAUTH: The redirect URI in the request did not match a registered redirect URI YouTube API to fetch all videos on a channel How do I get video durations with YouTube API version 3? Youtube API Limitations Stop embedded youtube iframe? How can I get a channel ID from YouTube? Embed YouTube Video with No Ads