Billybobbonnet
Billybobbonnet

Reputation: 3226

How can I pause an embedded Youtube video with vanilla Javascript?

I try to pause an iframe embedded YouTube video without a video-related event trigger.

I have read the youtube embedded api, this answer and this one and here is what I have so far (the video wont play in the snippet because of a CORS issue, but I guess it doesn't really matter.):

<iframe id="video1" width="560" height="315" src="http://www.youtube.com/embed/JFBUJ6kNl28" frameborder="0" allowfullscreen></iframe>

<script type="text/javascript">
  //youtube api to pause video when changing section
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player = false

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('video1', {});
  }

  function jump() {
    console.log(player);
    if (player) {
      player.pauseVideo()
    }
  }
</script>
<button type="button" onclick="jump()" name="button">pause button</button>

What am I missing? The player object is there when I log it but it throws me a player.pauseVideo() is not a function

Upvotes: 2

Views: 13027

Answers (3)

Must Ckr
Must Ckr

Reputation: 370

You can simply use:

iframe.contentWindow.postMessage(message, origin);

to send message to iframeWindow, from parentWindow. All popular video services support listening those messages.

Check out the link below for the live demo:

https://codepen.io/mcakir/pen/JpQpwm

NOTE: The live demo checks whether or not the videos are in the ViewPort. The code block i use supports play/pause iframe videos from Youtube, vimeo and dailymotion (more will be added soon) without using any player's libraries or SDK's.

Upvotes: 0

Sandeep Saini
Sandeep Saini

Reputation: 1

<a onclick="playVideoFunction()">Play video</a>
<a onclick="stopVideoFunction()">Stop video</a>

<iframe id="videoIframe" width="840" height="473" 
src="https://www.youtube.com/embed/dZ0fwJojhrs?feature=oembed" 
frameborder="0" allowfullscreen></iframe>

<script type="text/javascript">
function playVideoFunction() { 
  document.getElementById("videoIframe").src += "&autoplay=1";}

function stopVideoFunction() { 
  var ysrc = document.getElementById("videoIframe").src;    
  var newsrc = ysrc.replace("&autoplay=1", "");
  document.getElementById("videoIframe").src = newsrc;
}
</script>

Upvotes: -4

Billybobbonnet
Billybobbonnet

Reputation: 3226

I found the solution: as described in this answer, you need to add ?enablejsapi=1 to the video URL

A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1

Somehow, it doesn't work with my snippet but works in my real case.

Upvotes: 4

Related Questions