1

I couldn't use <video> tag for youtube video so I embed youtube inside a <iframe> as below to play a youtube video:

<iframe type="text/html" 
    width="640" 
    height="385" 
    src="http://www.youtube.com/embed/VIDEO_ID"
    frameborder="0">
</iframe>

It works fine to play the video. But I need to support press escape key to stop playing the video. Below code works for a <video> tag but it doesn't work for the iframe when the video is playing. It seems that the video takes keyboard control while playing. Is there a way for me to listen on keyboard event of the youtube iframe?

window.addEventListener('keydown',(e) => {
    if (e.key === 'Escape') {
         ...
    }
});

I tried to play the video via youtube api iframe, but the keydown event is not triggered when the video is playing. This code can be found: https://codepen.io/zhaoyi0113/pen/YJvJay. The event listener is not triggered if the video get focus and playing.

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523

2 Answers2

0

This is the proper way to add Iframe of youtube video using The youtube api iframe, check this code hope it will help you ( The video won't run, copy the code and run it in your browser) :

<!DOCTYPE html>
<html>

<body>

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

<script>

// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
 player = new YT.Player('player', {
  height: '360',
  width: '640',
  videoId: 'M7lc1UVf-VE',
  events: {
   'onReady': onPlayerReady,
   'onStateChange': onPlayerStateChange
  }
 });
}

// The API will call this function when the video player is ready.
function onPlayerReady(event) {
 event.target.playVideo();
}

//    The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;

function onPlayerStateChange(event) {
 if (event.data == YT.PlayerState.PLAYING && !done) {
  setTimeout(stopVideo, 6000);
  done = true;
 }
}

// Stop video
function stopVideo() {
 player.stopVideo();
}

// Your event listener on keydown
document.addEventListener('keydown',(e) => {
 alert("video will be stoped !!");
    if (e.key === 'Escape') {
         stopVideo()
    }
}, false);

</script>
</body>

</html>
Djamel Kr
  • 759
  • 1
  • 4
  • 14
0

You will have to use YouTube's IFrame Player API to achieve what you want. The code will inject the required api, create iframe on your page and load the video whose id you provide:

HTML:

<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

JavaScript:

// 1. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 2. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'M7lc1UVf-VE',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// The API will call this function when the video player is ready.
function onPlayerReady(event) {
    event.target.playVideo();
}
// Pause the video
function pauseVideo() {
    player.pauseVideo();
}
// your existing code
window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        pauseVideo();
    }
});

For detailed information use their API Reference

YouTube player does not allow to customize keyboard shortcuts and you cannot listen to browser events when video is focused. By the way, you can use spacebar to play/pause the video.

Pal Singh
  • 1,964
  • 1
  • 14
  • 29
  • I tried your solution. It works perfect to play the video via youtube api iframe, but the keydown event is not triggered when the video is playing. – Joey Yi Zhao Oct 21 '18 at 09:30
  • Note that when you are focused on the Video (when you clicked it), keyboard events won't work because video is playing in different frame. If you click outside the video and try escape key, video will pause. – Pal Singh Oct 21 '18 at 12:46
  • YouTube has its own set of keyboard shortcuts, for example pressing space will play/pause the video. – Pal Singh Oct 21 '18 at 15:09
  • is there a way to listen on YouTube own keyboard shortcuts? – Joey Yi Zhao Oct 22 '18 at 02:51
  • Events are not being propagated, so you cannot listen to them. – Pal Singh Oct 22 '18 at 04:00