Joey Yi Zhao
Joey Yi Zhao

Reputation: 42556

How to add keydown event on iframe while playing youtube video?

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.

Upvotes: 1

Views: 2417

Answers (2)

Pal Singh
Pal Singh

Reputation: 1974

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.

Upvotes: 0

Djamel Korei
Djamel Korei

Reputation: 774

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>

Upvotes: 0

Related Questions