I want to listen for a keydown event of an iframe in reactjs. In my iframe i have video embedded. Now when the video is playing i want to handle keyboard events.Can any one please help me how to listen for keyboard events. This is my code
class VideoDetail extends Component {
videoLoad(e) {
console.log('videoLoaded');
this.videoFrame.addEventListener('keydown',this.onVideoDown);
}
onVideoDown(e) {
console.log('key pressed'); // This is not invoking
}
componentDidMount() {
console.log(this.videoFrame);
}
render() {
const video = this.props.video;
if (!video) {
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe ref={(iframe) => { this.videoFrame = iframe; console.log(iframe); }} className="embed-responsive-item" src={url} onLoad={(e) => this.videoLoad(e)}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
}
}
You can catch the iframe keydown
event with iframe.contentWindow.document
as below using either e.target
or this.videoFrame
with the ref
.
Modified code
videoLoad(e) {
console.log('videoLoaded');
var iframe = e.target; // it is equal to "this.videoFrame" and so, you can avoid using "ref"
//this.videoFrame.addEventListener('keydown',this.onVideoDown);
iframe.contentWindow.document.addEventListener('keydown', this.onVideoDown);
}