Javascript YouTube API-iframe onStateChange事件
我使用的是iframe YouTube API,我想跟踪事件,例如,当用户启动和停止视频时,向google analytics发送数据Javascript YouTube API-iframe onStateChange事件,javascript,youtube,youtube-api,Javascript,Youtube,Youtube Api,我使用的是iframe YouTube API,我想跟踪事件,例如,当用户启动和停止视频时,向google analytics发送数据 <iframe src="https://www.youtube.com/embed/DjB1OvEYMhY"></iframe> 我看了看,没有找到一个例子如何做到这一点。该示例创建iframe并定义onReady和onStateChange。当我在页面上只有iframe时,我将如何执行相同的操作?此示例将侦听用户使用onPlay
<iframe src="https://www.youtube.com/embed/DjB1OvEYMhY"></iframe>
我看了看,没有找到一个例子如何做到这一点。该示例创建iframe并定义onReady和onStateChange。当我在页面上只有iframe时,我将如何执行相同的操作?此示例将侦听用户使用
onPlayerStateChange
及其不同属性进行的每个播放/暂停操作,并打印(记录)它们
但是,您需要创建自己的记录
函数来处理这些数据
您还需要在iframe(本例中为#player)上添加一个ID,并在其URL末尾添加?enablejsapi=1。当然,一定要包括
注意
在代码之后声明API很重要,因为它在准备就绪时调用onYouTubeIframeAPIReady
<!DOCTYPE html>
<html>
<body>
<iframe id="player" src="https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1"></iframe>
<h5>Record of user actions:</h5>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player( 'player', {
events: { 'onStateChange': onPlayerStateChange }
});
}
function onPlayerStateChange(event) {
switch(event.data) {
case 0:
record('video ended');
break;
case 1:
record('video playing from '+player.getCurrentTime());
break;
case 2:
record('video paused at '+player.getCurrentTime());
}
}
function record(str){
var p = document.createElement("p");
p.appendChild(document.createTextNode(str));
document.body.appendChild(p);
}
</script>
<script src="https://www.youtube.com/iframe_api"></script>
</body>
</html>
用户操作记录:
var播放器;
函数onyoutubeiframeapiredy(){
player=新的YT.player('player'{
事件:{'onStateChange':onPlayerStateChange}
});
}
函数onPlayerStateChange(事件){
开关(事件数据){
案例0:
录制(“视频结束”);
打破
案例1:
录制('从'+player.getCurrentTime())播放视频);
打破
案例2:
录制('视频暂停在'+player.getCurrentTime());
}
}
功能记录(str){
var p=document.createElement(“p”);
p、 appendChild(document.createTextNode(str));
文件.正文.附件(p);
}
这里有一个版本不使用Youtubes iframe API脚本。唯一的缺点是iframeapi可能会更改
<iframe id="player" src="https://www.youtube.com/embed/dQw4w9WgXcQ?enablejsapi=1"></iframe>
有时,事件加载不足以确保iframe中的文档准备就绪。如果iframe位于不同的域中,则无法订阅以查看它何时准备就绪 一种可能的解决方法是记录何时从iframe接收到事件,如果订阅后未接收到事件,请重试:
var addYoutubeEventListener = (function() {
var callbacks = [];
var iframeId = 0;
var subscribed = [];
return function (iframe, callback) {
// init message listener that will receive messages from youtube iframes
if(iframeId === 0) {
window.addEventListener("message", function (e) {
if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
try {
var data = JSON.parse(e.data);
subscribed[data.id] = true;
if(data.event !== 'onStateChange') return;
var callback = callbacks[data.id];
callback(data);
}
catch(e) {}
}, true);
}
// store callback
iframeId++;
callbacks[iframeId] = callback;
subscribed[iframeId] = false;
var currentFrameId = iframeId;
//console.log("adding event listener to iframe id " + iframeId);
// sendMessage to frame to start receiving messages
iframe.addEventListener("load", function () {
var tries = 0;
var checkSubscribed = function()
{
if (subscribed[currentFrameId]) {
//console.log("subscribed succesfully " + currentFrameId)
}
else
{
tries++;
//console.log("Try again " + currentFrameId + " (" + tries + ")");
if (tries < 100) {
doSubscribe();
}
else
{
console.log("Unable to subscribe" + currentFrameId );
}
}
}
var doSubscribe = function()
{
var message = JSON.stringify({
event: 'listening',
id: currentFrameId,
channel: 'widget'
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
message = JSON.stringify({
event: "command",
func: "addEventListener",
args: ["onStateChange"],
id: currentFrameId,
channel: "widget"
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
setTimeout(checkSubscribed, 100);
};
doSubscribe();
}, true);
}
})();
var addYoutubeEventListener=(函数(){
var回调=[];
var-iframeId=0;
风险值=[];
返回函数(iframe、回调){
//将从youtube iFrame接收消息的初始化消息侦听器
if(iframeId==0){
window.addEventListener(“消息”,函数(e){
如果(例如,原点!==”https://www.youtube.com“| | e.data==未定义)返回;
试一试{
var data=JSON.parse(e.data);
订阅的[data.id]=true;
if(data.event!=“onStateChange”)返回;
var callback=callbacks[data.id];
回调(数据);
}
捕获(e){}
},对);
}
//存储回调
iframeId++;
回调[iframeId]=回调;
订阅的[iframeId]=false;
var currentFrameId=iframeId;
//log(“将事件侦听器添加到iframe id”+iframeId);
//发送消息到帧以开始接收消息
iframe.addEventListener(“加载”,函数(){
var=0;
var checkSubscribed=函数()
{
如果(已订阅[currentFrameId]){
//console.log(“成功订阅”+currentFrameId)
}
其他的
{
尝试++;
//log(“重试”+currentFrameId+”(“+trys+”);
如果(尝试<100){
剂量订阅();
}
其他的
{
console.log(“无法订阅”+currentFrameId);
}
}
}
var doSubscribe=函数()
{
var message=JSON.stringify({
事件:“倾听”,
id:currentFrameId,
频道:“小部件”
});
iframe.contentWindow.postMessage(消息,'https://www.youtube.com');
message=JSON.stringify({
事件:“命令”,
func:“addEventListener”,
参数:[“onStateChange”],
id:currentFrameId,
频道:“小部件”
});
iframe.contentWindow.postMessage(消息,'https://www.youtube.com');
setTimeout(checkSubscribed,100);
};
剂量订阅();
},对);
}
})();
您应该能够按照函数getPlayerState(){if(ytplayer){return ytplayer.getPlayerState();}}}的思路放入事件处理程序-希望有人能够演示这是如何产生结果的。恐怕我帮不了你。
addYoutubeEventListener(document.getElementById("player"), function(e) {
switch(e.info) {
case 1:
// playing
break;
case 0:
// ended
break;
}
});
var addYoutubeEventListener = (function() {
var callbacks = [];
var iframeId = 0;
var subscribed = [];
return function (iframe, callback) {
// init message listener that will receive messages from youtube iframes
if(iframeId === 0) {
window.addEventListener("message", function (e) {
if(e.origin !== "https://www.youtube.com" || e.data === undefined) return;
try {
var data = JSON.parse(e.data);
subscribed[data.id] = true;
if(data.event !== 'onStateChange') return;
var callback = callbacks[data.id];
callback(data);
}
catch(e) {}
}, true);
}
// store callback
iframeId++;
callbacks[iframeId] = callback;
subscribed[iframeId] = false;
var currentFrameId = iframeId;
//console.log("adding event listener to iframe id " + iframeId);
// sendMessage to frame to start receiving messages
iframe.addEventListener("load", function () {
var tries = 0;
var checkSubscribed = function()
{
if (subscribed[currentFrameId]) {
//console.log("subscribed succesfully " + currentFrameId)
}
else
{
tries++;
//console.log("Try again " + currentFrameId + " (" + tries + ")");
if (tries < 100) {
doSubscribe();
}
else
{
console.log("Unable to subscribe" + currentFrameId );
}
}
}
var doSubscribe = function()
{
var message = JSON.stringify({
event: 'listening',
id: currentFrameId,
channel: 'widget'
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
message = JSON.stringify({
event: "command",
func: "addEventListener",
args: ["onStateChange"],
id: currentFrameId,
channel: "widget"
});
iframe.contentWindow.postMessage(message, 'https://www.youtube.com');
setTimeout(checkSubscribed, 100);
};
doSubscribe();
}, true);
}
})();