具有现有iframe [src]绑定的Angular 2+ Youtube Iframe API无法运行事件

时间:2019-03-07 19:00:09

标签: javascript angular typescript iframe youtube-api

我遇到了youtube iframe API无法在现有iframe上运行事件回调的问题。

如果我使用:

<div id="player"></div>

有效

但是如果我使用:

 <iframe id="player" [src]="mainVideo | sanitize"
 width="560" height="315" frameborder="0" allowfullscreen></iframe>

它不会加载任何事件回调,例如当该人完成视频时自动播放或发出警报。

HTML

 <iframe id="player" [src]="mainVideo | sanitize"
 width="560" height="315" frameborder="0" allowfullscreen></iframe>

打字稿

 ngAfterViewInit() {
    const doc = (<any>window).document;
    let script = doc.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://www.youtube.com/iframe_api';
    doc.body.appendChild(script);
    console.log(script);
}

ngOnInit() {
    (<any>window).onYouTubeIframeAPIReady = () => {
        console.log((<any>window).YT);
        this.player = new (<any>window).YT.Player('player',
            {
                events: {
                    'onReady': (e) => {
                        e.target.playVideo();
                    },
                    'onStateChange': (e) => {
                        if (e.data === 0) {
                            alert('done');
                        }
                    }
                }
            });
    }
}

MainVideo

this.mainVideo = "http://www.youtube.com/embed/" 
+ this.sect[0].mainVideoUrl + "?origin=http://localhost:56194&enablejsapi=1";

有人可以帮助我了解其发生原因吗?单击播放时,视频本身会播放,但不会自动播放,并且在视频播放完成时也不会提醒用户。

谢谢!

0 个答案:

没有答案