us0343
us0343

Reputation: 7

I want to play a welcome voice when my web page loads but don't on reload the web page

I have Added an auto-play welcome voice or audio in my web page for new visitors.But when, visitors reload the web page the welcome voice plays again.I don't want to play it again when visitor reload the web page. Can anyone can guide me? My code is here:

<script type="text/javascript">
 var audioElement = document.createElement('audio');
 audioElement.setAttribute('src', 'filepath/audiofile.wav');
 audioElement.play();
</script>

Upvotes: 0

Views: 916

Answers (2)

Rami Sakr
Rami Sakr

Reputation: 372

What you need to do is set a cookie that works as a flag to check if the page has loaded before or not,

<script>

    function setCookie(cname,cvalue,exdays)
    {
    var d = new Date();
    d.setTime(d.getTime()+(exdays*24*60*60*1000));
    var expires = "expires="+d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
    }

    function getCookie(cname)
    {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) 
      {
      var c = ca[i].trim();
      if (c.indexOf(name)==0) return c.substring(name.length,c.length);
      }
    return "";
    }


    window.onload=function(){
    if(getCookie('hasPlayed') != null){

    var audioElement = document.createElement('audio');
     audioElement.setAttribute('src', 'filepath/audiofile.wav');
     audioElement.play();
    setCookie('hasPlayed', true, NUMBER-OF-DAYS-TO-KEEP-COOKIE);
    }

};

</script>

Upvotes: 4

user1186816
user1186816

Reputation: 1

You can use web storage to know if the page is visit for the first time or is a reload. http://www.html5rocks.com/en/features/storage

Upvotes: 0

Related Questions