【发布时间】:2013-03-28 02:10:06
【问题描述】:
我有一个系统,主要内容是通过 ajax 加载的,在主“框架”的 div 内。
在某些页面中,我需要跟踪用户播放完视频的时间。我正在尝试使用 youtube iframe api。它工作正常,但我正在处理一些奇怪的事情。
主要问题:用户观看完视频后发生的操作在每个页面上都不同,不知何故,API 将所有功能堆叠在一起并同时运行。
例如,我有第一页,它是通过 ajax 加载的,并且有这个 sn-p 来加载 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>
它工作正常。但是,我为我的第二页加载了内容,现在问题开始了:
<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 会被调用两次,一次调用 actionToScreen1,另一次调用 actionToScreen2。看起来我只是通过 ajax 加载容器,该函数在某种程度上是全局存储的,但我找不到在哪里,也找不到区分正在调用哪个函数的方法。我该如何解决这个问题?
【问题讨论】:
-
是否有可能在 Screen2 加载后移除 Screen1 DOM?
标签: youtube youtube-api