Setting Cookies in browser for video autoplay

前端 未结 3 1758
陌清茗
陌清茗 2021-01-07 08:21

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?

相关标签:
3条回答
  • 2021-01-07 08:53

    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.

    0 讨论(0)
  • 2021-01-07 08:59

    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

    0 讨论(0)
  • 2021-01-07 09:09

    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>
    
    0 讨论(0)
提交回复
热议问题