更改iframe父容器后,youtube iframe播放器未触发事件

时间:2018-09-18 01:51:53

标签: javascript typescript youtube-api

在我的应用程序中,我需要更改YouTube iframe所在的容器。更改容器后,不会触发状态更改事件(onStateChange)。但是,每次更改父项时,都会调用ready事件(onReady)。 我试图将“ addEventListener”添加到onReady事件处理程序中,但是它不起作用,并且事件未触发。 例如:

export class YouTubePlayer
{
    private player: YT.Player;
    private ready: boolean = false;

    public Init(): void
    {
        (<any>window).onYouTubeIframeAPIReady = () =>
        {
            console.log("VideoPlayer onYouTubeIframeAPIReady");

            this.player = new YT.Player('player', {
                height: '800px',
                width: '600px',
                playerVars: { 'modestbranding': 1, 'disablekb': 1, 'showinfo': 0, 'autoplay': 0 },
                events: {
                    'onReady': (ev: YT.PlayerEvent) =>
                    {
                        if (this.ready)
                        {
                            //It's not working for me. Events not firing after change parent container
                            ev.target.addEventListener("onStateChange", (evTwice: YT.PlayerEvent) =>
                            {
                                console.log("VideoPlayer: I'm alive!!!");
                            });

                            this.player.addEventListener("onStateChange", (evTwice: YT.PlayerEvent) =>
                            {
                                console.log("VideoPlayer: I'm alive too!!!");
                            });

                            return;
                        }

                        this.ready = true;

                        setInterval(() => { this.player.loadVideoById("lArqtUE2w3o"); }, 5000);
                    },
                    'onStateChange': (ev: YT.PlayerEvent) =>
                    {
                        //Events not firing after change parent container
                        console.log("VideoPlayer change state: " + ev['data']);
                    }
                }
            });
        };

        console.log("VideoPlayer init");
        let script = window.document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://www.youtube.com/iframe_api";
        window.document.body.appendChild(script);
    }
}

我不明白为什么事件会停止被调用以及如何使事件返回

0 个答案:

没有答案