Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

player.removeEventListener of youtube-iframe-api not working

Through my observation, the removeEventListener in the API is a little different from that for a dom. There is no "once" option, so I need to manually remove the listener after it triggered. However, it doesn't work.

The code, for example, is like this (for some reasons you cannot run it directly. You need to copy it into an HTML file and open it in a browser, open the dev-tool to see the console.):

/*Load & auto-play youtube video*/
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Replace #ytPlayer element with an <iframe> and
// YouTube ytPlayer after the API code downloads.
var ytPlayer;
function onYouTubePlayerAPIReady(){
    ytPlayer = new YT.Player("ytPlayer", {
        height: "80%",
        width: "100%",
        videoId: "9pWXAEZ5NLs",
        playerVars: {
            controls: 0, 
            disablekb: 1, /* disablekb is to remove all the keyboard shortcuts (especially NUMBER). Add back or change some of them later. */
            iv_load_policy:3,
            rel: 0,
            fs: 0
        },
        events:{
            "onReady": (event)=>{
                var sayStateChanged = ()=>{
                    console.log("State is CHANGED! This event listener should be removed.");
                    ytPlayer.addEventListener("onStateChange", sayStateChanged);
                };
                ytPlayer.addEventListener("onStateChange", sayStateChanged);
            }
        }
    });
}
<div id="ytPlayer"></div>
question from:https://stackoverflow.com/questions/65540859/player-removeeventlistener-of-youtube-iframe-api-not-working

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...