How would I set cookies such that a video only plays automatically on the first visit only, afterwards if they want to watch it, it must be played manually?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
The general idea would be:
on page load retrieve cookie information
if no cookie, or its set to false, play the movie
set cookie to true
回答2:
Here's what I used on a project:
if (document.cookie.length == 0 || document.cookie.indexOf("MYCOOKIENAME=") == -1) {
// I set the path to / so once they'd seen it once on the site they wouldn't
// see it on other pages.
document.cookie = "MYCOOKIENAME=true; path=/;";
// START VIDEO PLAYING HERE.
}
I didn't really want the overhead of adding a cookie library.
Plugging my code into Oliver Moran's HTML gives you:
<iframe title="YouTube video player" id="videoframe" width="480" height="390" src="" frameborder="0" allowfullscreen></iframe>
<script language="javascript">
var link = "http://www.youtube.com/embed/he5fpsmH_2g";
if (document.cookie.length == 0 || document.cookie.indexOf("MYCOOKIENAME=") == -1) {
// I set the path to / so once they'd seen it once on the site they wouldn't
// see it on other pages.
document.cookie = "MYCOOKIENAME=true; path=/;";
link += "?autoplay=1"; // append an autoplay tag to the video URL
}
document.getElementById("videoframe").src = link; // set the iframe src
</script>
回答3:
Per Justin808's answer, the general idea would be like this:
if (!cookieIsSet()) {
setCookie();
playMovie();
}
See the W3Schools site for an example use of cookies similar to what you want to achieve: http://www.w3schools.com/js/js_cookies.asp
If you are embedding a YouTube video you could do it like this:
<iframe title="YouTube video player" id="videoframe" width="480" height="390" src="" frameborder="0" allowfullscreen></iframe>
<script language="javascript">
var link = "http://www.youtube.com/embed/he5fpsmH_2g";
if (!cookieIsSet()) {
setCookie();
link += "?autoplay=1"; // append an autoplay tag to the video URL
}
document.getElementById("videoframe").src = link; // set the iframe src
</script>
Obviously, you would have to define your own cookieIsSet()
and setCookie()
functions. See the W3School's site for examples how.