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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…