Setting Cookies in browser for video autoplay

本小妞迷上赌 提交于 2019-12-19 05:00:11

问题


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:

  1. on page load retrieve cookie information

  2. if no cookie, or its set to false, play the movie

  3. 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.



来源:https://stackoverflow.com/questions/5480444/setting-cookies-in-browser-for-video-autoplay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!