メインの「フレーム」のdiv内に、メインコンテンツがajaxを介してロードされるシステムがあります。
一部のページでは、ユーザーがいつビデオの再生を終了したかを追跡する必要があります。YouTube iframe api を使用しようとしています。それは問題なく動作しますが、私はいくつかの奇妙なことを実行しています。
主な問題: ユーザーがビデオの視聴を終了したときに発生するアクションがページごとに異なり、API がすべての関数をスタックして一度に実行しています。
例として、ajax を介して読み込まれる最初のページがあり、YouTube ビデオを読み込むための次のスニペットがあります。
<script>
// 2. This code loads the IFrame Player API code asynchronously.
if (window.YT)
{
window.YT = undefined;
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player = undefined;
function onYouTubeIframeAPIReady() {
player = new YT.Player('divVideo', {
playerapiid: 'somecode',
height: '309',
width: '439',
videoId: 'somecode',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
actionToScreen1()
}
}
</script>
それは正常に動作します。しかし、その後、ページ 2 のコンテンツを読み込むと、問題が発生します。
<script>
// 2. This code loads the IFrame Player API code asynchronously.
if (window.YT)
{
window.YT = undefined;
}
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player = undefined;
function onYouTubeIframeAPIReady() {
player = new YT.Player('divVideo', {
playerapiid: 'anothercode',
height: '309',
width: '439',
videoId: 'anothercode',
events: {
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED ) {
actionToScreen2()
}
}
</script>
screen2 のビデオが終了すると、onPlayerStateChange が 2 回呼び出されます。1 回は actionToScreen1 を呼び出し、もう 1 回は actionToScreen2 を呼び出します。私は ajax を介してコンテナーをロードしているように見えますが、関数は多少グローバルに保存されていますが、どこにあるのかわかりませんし、どの関数が呼び出されているのかを区別する方法も見つかりません。どうすればこれを修正できますか?