【问题标题】:How to listen iframe keydown event with ReactJS如何使用 ReactJS 监听 iframe keydown 事件
【发布时间】:2017-09-20 01:47:15
【问题描述】:

我想在 reactjs 中监听 iframe 的 keydown 事件。在我的 iframe 中,我嵌入了视频。现在,当视频播放时,我想处理键盘事件。任何人都可以帮助我如何收听键盘事件。这是我的代码

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

}

【问题讨论】:

    标签: javascript html reactjs iframe keydown


    【解决方案1】:

    您可以使用iframe.contentWindow.document 捕获iframe keydown 事件,如下所示,使用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);
    }
    

    【讨论】:

    • 感谢您的回复阿鲁纳。添加您的行后,我收到此错误。未捕获的 DOMException: Blocked a frame with origin "localhost:8080" from access a cross-origin frame.
    • @Trinu,这是在Same-origin security policy 下,因为您正尝试使用 javascript 从另一个域访问一个域。如果两个域相同,那么上面的代码将毫无问题地工作,否则如果您只是为了测试而创建页面,则必须禁用浏览器安全性。请看一下这个网址,stackoverflow.com/a/25098153/7055233
    • 我已经在 osx -a Google\ Chrome --args --disable-web-security --user-data-dir 中执行了这个命令。这次我没有收到错误,但是 keydown 事件没有触发.. 无法监听 keydown 事件。
    • 我希望你尝试过这个,$ open -a Google\ Chrome --args --disable-web-security --user-data-dir 在 OSX 中
    • 你能给我一个用于this.props.video的样本数据吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多