Reputation: 7
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
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
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