1
我想在reactjs中監聽iframe的keydown事件。在我的iframe中嵌入了視頻。現在,當視頻播放時,我想處理鍵盤事件。任何人都可以幫助我如何聽鍵盤事件。這是我的代碼如何使用ReactJS監聽iframe keydown事件
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>
);
}
}
感謝您的回覆阿魯娜。添加行後出現此錯誤。未定義DOMException:阻止源「http:// localhost:8080」訪問跨源幀的框架。 – Trinu
@Trinu,這是來自'同源安全策略',因爲您試圖使用JavaScript從另一個域訪問一個域。如果兩個域都是相同的,那麼上面的代碼將毫無問題地工作,否則如果您只是爲了測試而創建頁面,則必須禁用瀏覽器安全性。請看看這個網址,http://stackoverflow.com/a/25098153/7055233 – Aruna
我在osx -a Google \ Chrome中執行了這個命令--args --disable-web-security --user-data- DIR。這一次,我沒有得到錯誤,但keydown事件沒有發射..無法聽到keydown事件。 – Trinu