网站搜索

javascript - Angular 2+ 使用现有 iframe [src] 绑定的 Youtube Iframe 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";

有人能帮我理解为什么会发生这种情况吗?视频本身在点击播放时可以播放,但它不会自动播放,也不会在视频播放结束时提醒用户。

谢谢!