2017-04-23 101 views
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> 
    ); 
} 

} 

回答

1

您可以iframe.contentWindow.document趕上了iframe​​事件如下使用或者e.targetthis.videoFrameref

修改後的代碼

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); 
} 
+0

感謝您的回覆阿魯娜。添加行後出現此錯誤。未定義DOMException:阻止源「http:// localhost:8080」訪問跨源幀的框架。 – Trinu

+0

@Trinu,這是來自'同源安全策略',因爲您試圖使用JavaScript從另一個域訪問一個域。如果兩個域都是相同的,那麼上面的代碼將毫無問題地工作,否則如果您只是爲了測試而創建頁面,則必須禁用瀏覽器安全性。請看看這個網址,http://stackoverflow.com/a/25098153/7055233 – Aruna

+0

我在osx -a Google \ Chrome中執行了這個命令--args --disable-web-security --user-data- DIR。這一次,我沒有得到錯誤,但keydown事件沒有發射..無法聽到keydown事件。 – Trinu