Stop embedded youtube iframe?

199,990

Solution 1

You may want to review through the Youtube JavaScript API Reference docs.

When you embed your video(s) on the page, you will need to pass this parameter:

http://www.youtube.com/v/VIDEO_ID?version=3&enablejsapi=1

If you want a stop all videos button, you can setup a javascript routine to loop through your videos and stop them:

player.stopVideo()

This does involve keeping track of all the page IDs for each video on the page. Even simpler might be to make a class and then use jQuery.each.

$('#myStopClickButton').click(function(){
  $('.myVideoClass').each(function(){
    $(this).stopVideo();
  });
});

Solution 2

Unfortunately these API's evolve very fast. As of May 2015, the proposed solutions don't work anymore, as the player object has no stopVideo method.

A reliable solution is to be found in this page (1) and it works with an:

<iframe id="youtube_player" class="yt_player_iframe" width="640" height="360" src="http://www.youtube.com/embed/aHUBlv5_K8Y?enablejsapi=1&version=3&playerapiid=ytplayer"  allowfullscreen="true" allowscriptaccess="always" frameborder="0"></iframe>

and the following JS/jQuery code:

$('.yt_player_iframe').each(function(){
  this.contentWindow.postMessage('{"event":"command","func":"stopVideo","args":""}', '*')
});

Solution 3

If anyone is still looking for the answer, i've solved it like so:

$("#photos").on("hide",function(){
    var leg=$('.videoPlayer').attr("src");
    $('.videoPlayer').attr("src",leg);
});

Where #photos is the ID of the modal and .videoPlayer is the class of the iframe. Basically it refreshes the src attribute (and stops playing the video). So,

    $('#myStopClickButton').click(function(){
      $('.yvideo').each(function(){
        var el_src = $(this).attr("src");
        $(this).attr("src",el_src);
      });
    });

should do the trick.

Solution 4

Here is a codepen, it worked for me.

I was searching for the simplest solution for embedding the YT video within an iframe, and I feel this is it.

What I needed was to have the video appear in a modal window and stop playing when it was closed

Here is the code : (from: https://codepen.io/anon/pen/GBjqQr)

    <div><a href="#" class="play-video">Play Video</a></div>
    <div><a href="#" class="stop-video">Stop Video</a></div>
    <div><a href="#" class="pause-video">Pause Video</a></div>

    <iframe class="youtube-video" width="560" height="315" src="https://www.youtube.com/embed/glEiPXAYE-U?enablejsapi=1&version=3&playerapiid=ytplayer" frameborder="0" allowfullscreen></iframe>

$('a.play-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'playVideo' + '","args":""}', '*');
});

$('a.stop-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'stopVideo' + '","args":""}', '*');
});

$('a.pause-video').click(function(){
    $('.youtube-video')[0].contentWindow.postMessage('{"event":"command","func":"' + 'pauseVideo' + '","args":""}', '*');
});

Additionally, if you want it to autoplay in a DOM-object that is not yet visible, such as a modal window, if I used the same button to play the video that I was using to show the modal it would not work so I used THIS:

https://www.youtube.com/embed/EzAGZCPSOfg?autoplay=1&enablejsapi=1&version=3&playerapiid=ytplayer

Note: The ?autoplay=1& where it's placed and the use of the '&' before the next property to allow the pause to continue to work.

Solution 5

APIs are messy because they keep changing. This pure javascript way worked for me:

 <div id="divScope" class="boom-lightbox" style="display: none;">
    <iframe id="ytplayer" width="720" height="405"   src="https://www.youtube.com/embed/M7lc1UVf-VE" frameborder="0" allowfullscreen>    </iframe>
  </div>  

//if I want i can set scope to a specific region
var myScope = document.getElementById('divScope');      
//otherwise set scope as the entire document
//var myScope = document;

//if there is an iframe inside maybe embedded multimedia video/audio, we should reload so it stops playing
var iframes = myScope.getElementsByTagName("iframe");
if (iframes != null) {
    for (var i = 0; i < iframes.length; i++) {
        iframes[i].src = iframes[i].src; //causes a reload so it stops playing, music, video, etc.
    }
}
Share:
199,990
Danpe
Author by

Danpe

Check out GlobeKeeper.

Updated on February 21, 2022

Comments

  • Danpe
    Danpe about 2 years

    I'm using YouTube iframe to embed videos on my site.

    <iframe width="100%" height="443" class="yvideo" id="p1QgNF6J1h0"
                  src="http://www.youtube.com/embed/p1QgNF6J1h0?rel=0&controls=0&hd=1&showinfo=0&enablejsapi=1"
                  frameborder="0" allowfullscreen>
    </iframe>
    

    And i have multiplie videos on the same page.

    I want to stop all of them or one of them in a click of a button using javascript or so.

    Is it possible?

    UPDATE:

    I tried what Talvi Watia said and used:

    $('#myStopClickButton').click(function(){
      $('.yvideo').each(function(){
        $(this).stopVideo();
      });
    });
    

    I'm getting:

    Uncaught TypeError: Object [object Object] has no method 'stopVideo' 
    
  • Danpe
    Danpe about 11 years
    But i will need to create an object for each player? Will the stopVideo() just work without any prior setups ?
  • Talvi Watia
    Talvi Watia about 11 years
    If you add enablejsapi=1 to the embed you should be able to reference the API. It will need to be added for every video.
  • Danpe
    Danpe about 11 years
    I'm getting: Uncaught TypeError: Object [object Object] has no method 'stopVideo'
  • Talvi Watia
    Talvi Watia about 11 years
    stackoverflow.com/questions/9310112/… has information about the cross-site prtection error. (normally a huge issue in chrome.) as for the second, you need to change .myVideoClass with the class attached to your embed. i.e. .yvideo
  • Danpe
    Danpe about 11 years
    I think it's a problem that my onYouTubePlayerReady not being called.
  • Talvi Watia
    Talvi Watia about 11 years
    entirely possible. Again, I would recommend to follow the API guide, possibly try some examples. Also make sure you allow the cross-origin script. Access-Control-Allow-Origin: *
  • Talvi Watia
    Talvi Watia about 11 years
    @Danpe It appears a full working example can be found here: stackoverflow.com/questions/7443578/…
  • Eskat0n
    Eskat0n about 10 years
    stopVideo is native and not a jQuery method, so do not wrap your iframe in jQuery. I also recommend to use <object> tag instead of <iframe> for embedding YT videos.
  • Talvi Watia
    Talvi Watia about 10 years
    @Eskat0N again, I would recommend to use the working example. To use the (quick and easy) method I provided, you need to include jquery in your header. stopVideo is actually not a native function to javascript, rather the embedded YouTube player object. Thus, if you reference by id or class in jQuery, it really doesn't matter if it is an object or iframe. (Although <object> is better yes.) The subfunctions bound to that object will then be available in jQuery. (such as stopVideo)
  • Ionut
    Ionut over 7 years
    I think this is the best option when you load iframes dinamically.
  • rtpHarry
    rtpHarry over 7 years
    Good tip, thanks. I incorporated :visible into it so instead of resetting everything on the page I just reset the current one. When flipping through tabs or a gallery it means the new tab will show with the video already loaded.
  • Marco Faustinelli
    Marco Faustinelli over 7 years
    With which version of the API have you falsified this solution? Have you found an alternative?
  • azhidkov
    azhidkov over 7 years
    I would like to emphasize that your embed url MUST have enablejsapi=1, otherwise this doesn't work. Details here developers.google.com/youtube/player_parameters#enablejsapi I spent some time when I realized why this answer doesn't work.
  • Alan Bellows
    Alan Bellows about 7 years
    Perhaps something changed on the YouTube end, but for me this just restarts the video rather than stopping it (edit: nevermind, javascript elsewhere was adding '&autoplay=1' to the url)
  • MastaBaba
    MastaBaba almost 7 years
    A fine hack. Applause.
  • kneidels
    kneidels over 6 years
    perfect as of now
  • Shah Abaz Khan
    Shah Abaz Khan about 6 years
    Ha! Take that YouTube! Smart people scores!
  • Alex R
    Alex R about 6 years
    This is still working as of 5/2018. Fixed a cosmetic typo in the js code.
  • skinny_jones
    skinny_jones almost 6 years
    Hello there,does anyone know how to implement that within Ionic 3?
  • J.Kirk.
    J.Kirk. almost 6 years
    For some reason I had to pass it to the src link for it to work: src="youtube.com/embed/…"
  • Clint
    Clint almost 6 years
    Are the classes here intentionally different? yt_player_iframe vs youtube_player_iframe
  • Marco Faustinelli
    Marco Faustinelli almost 6 years
    @Clint: good catch. Looking at it now, I guess they should be the same; but I can't recall exactly what I did myself 3yrs ago. I see the original page with the solution is lost, so we are on our own. You may want to edit the text :-)
  • Marco Faustinelli
    Marco Faustinelli almost 6 years
    @NejcRodošek - I don't know. It appears the original page where I found this solution is lost forever. Possibly a reference to this API version is still reachable.
  • Nejc Rodošek
    Nejc Rodošek almost 6 years
    @MarcoFaustinell i found the command, it is: unMute. Its case sensitive, so watch out for the cases.
  • Chris Pink
    Chris Pink over 5 years
    note in this answer there is a mismatch between class="yt_player_iframe" and $('.youtube_player_iframe'), correct this and it works perfectly
  • Chris Pink
    Chris Pink over 5 years
    although it does throw a warning : "Cross-Origin Request Blocked" if more than one is playing.
  • CPHPython
    CPHPython over 5 years
    On 2018-11-20 just adding ?enablejsapi=1 to the URL and using the postMessage worked for me without importing any JS files for the Youtube API. When the warning shows up in teh console, it also says: "The Same Origin Policy disallows reading the remote resource at [URL] Reason: CORS request did not succeed".
  • E Benzle
    E Benzle over 4 years
    Yes! Thanks. This is option is still working in 2019. Also, it does not rely on YouTube API.
  • chifliiiii
    chifliiiii over 4 years
    seems to fail with ms edge.
  • Jax297
    Jax297 over 4 years
    @chifliiiii maybe it recognizes the same source wants to be loaded. Maybe you can try to insert a line "$(this).attr("src","#");" just before "$(this).attr("src",el_src);" ? let us know if that helps :)
  • TrySpace
    TrySpace over 4 years
    So with autoplay=1, the 1 means it should not pause (and play automatically), are you saying if you put the & after it it will not autoplay and pause the video?
  • Debbie Kurth
    Debbie Kurth over 4 years
    this is a close solution to was looking for. Now to detect if it is playing BEFORE I try the reset. It causes the video to blink.
  • okarpov
    okarpov about 4 years
    easiest way to stop player without all these JS and API from youtube, thx!
  • Simion Agavriloaei
    Simion Agavriloaei almost 4 years
    2020-05-25, this solution still works, add ?enablejsapi=1 and iframeElement.contentWindow.postMessage('{"event":"command",‌​"func":"pauseVideo",‌​"args":""}', '*') (notice i'm using pauseVideo, because stopVideo hides title even if the video was not started).
  • Marco Faustinelli
    Marco Faustinelli almost 4 years
    @CPHPython @SimionAgavriloaei - the src attribute of the iframe already contains enablejsapi=1, yet you both suggest to add the same string. But where? Feel free to edit the text, because I don't understand. Thank you for the upvote, btw! :-)
  • CPHPython
    CPHPython almost 4 years
    @MarcoFaustinelli I probably meant that the other 2 parameters were not needed, i.e. version and playerapiid do not need to be in the URL.
  • Nanoo
    Nanoo almost 4 years
    I know this post is old, but I just wanted to say that this solution still works as of July 2020.
  • djmzfKnm
    djmzfKnm over 3 years
    This didn't worked for me, instead this fiddle did the trick: jsfiddle.net/MadLittleMods/3J2wT with this code $('#popup-youtube-player')[0].contentWindow.postMessage('{"e‌​vent":"command","fun‌​c":"' + 'stopVideo' + '","args":""}', '*');
  • GitHunter0
    GitHunter0 about 3 years
    Hey folks, this solution is great, except that it makes the video lose all its native interactivity, how can I still use the native youtube video buttons? Thank you
  • Michał Tkaczyk
    Michał Tkaczyk over 2 years
    I think that it does not work anymore, at least on Chrome 96, I've also checked in Firefox 89.0.2 and it works, but not in Chrome :(
  • pacanga
    pacanga over 2 years
    Just tried as well, seems does not work. What might be new change. lol.
  • Boris Adamyan
    Boris Adamyan about 2 years
    NOTE enablejsapi=1 this attribute is required in URL