我处境艰难。
我正在尝试将自己播放的YouTube视频添加到我的网站上......我已经完成了... ...但是,有没有办法告诉这个人是否已经访问过这个网站,比如使用cookies,或更简单的东西(我不知道如何使用cookies哈哈)然后如果他们不止一次访问过网站就不自动播放?
我可以想象,如果你访问一个网站3到4次,它可能会非常烦人,每次你访问时这个视频都会继续播放!
这是我到目前为止的代码......
<iframe width="455" height="256" src="https://www.youtube.com/embed/qYTlJdYe0lw?rel=0&autoplay=1;showinfo=0" frameborder="0" allowfullscreen></iframe>
谢谢你提前帮忙!
答案 0 :(得分:1)
这里有一些jsfiddle的实例: Play youtube video only once at first page visit。 我正在使用Cookie和youtube JavaScript API。
<!-- html -->
<div id="video_container"></div>
//JavaScript
$(document).ready(function() {
//inject script tag in dom with iframe-api as source
//on success this will call function "onYouTubeIframeAPIReady"
//more info https://en.wikipedia.org/wiki/JSONP
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//this is only for testing reason
//remove cookie
$('button').on('click', function(){
document.cookie = "yt_video=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
});
});
var player;
function onYouTubeIframeAPIReady() {
//JavaScript API is loaded -> create player
//more info https://developers.google.com/youtube/iframe_api_reference#Getting_Started
player = new YT.Player('video_container', {
height: '390',
width: '640',
videoId: 'SzPfOuFvlfs',
events: {
'onReady': onPlayerReady
}
});
};
function onPlayerReady() {
//check if cookie exist. If not set one and play video
if (getCookie('yt_video') === '') {
document.cookie="yt_video=SzPfOuFvlfs";
player.playVideo();
}
}
// helper function
// get cookie value
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}