javascripthtmlvideo

Autoplay HTML video if url hash is present


I wrote some javascript to detect if a specific URL hash is present to automatically play a specific video when the page loads.

I am able to determine that the video play code is being activated via the togglevid() alert when the page loads. However, the video never starts playing.

Can you take a look at the code below and see what I am missing here?

if (window.location.hash) {
  // if "playvideo" hash is present, automatically start playing the video
  var runvid = document.getElementById(window.location.hash.slice(1)).getElementsByTagName('video').item(0);
  togglevid(runvid);
}

// Create listener for each video to play when clicked on
var vids = document.getElementsByTagName('video')
for (var i = 0; i < vids.length; i++) {
  var x = vids.item(i);
  vids.item(i).addEventListener("click", function() {
    togglevid(this);
  });
}

function togglevid(x) {
  alert("Video toggle triggered.  SRC: " + x.src);
  if (x.paused == true) x.play();
  else x.pause();
}
body {
  max-width: 800px;
}

video {
  max-width: 800px;
}
<h1>TEST</h1>
<p>Click on video to start playing if it hasn't already started.</p>
<div id="playvideo">
  <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"></video>
</div>


Solution

  • If you want to auto-play a video as soon as the page loads, without any user interaction, then it must be muted.

    Due to the Media Engagement Index implemented in modern browsers, you cannot auto play sound or un-muted video without the user having first interacted with the page to show engagement with your content.

    Here's a working example, where I have added muted="true" to your video so that it plays. Note that I removed the logic around handling the hash in the URL as it's not relevant to the problem:

    const vids = document.querySelectorAll('video');
    vids.forEach(vid => {
      vid.addEventListener("click", e => togglevid(e.currentTarget));
    });
    
    const togglevid = video => video.paused ? video.play() : video.pause();
    
    // add your URL hash logic back in here...
    const runvid = document.querySelectorAll('#playvideo video')[0];
    togglevid(runvid);
    body {
      max-width: 800px;
    }
    
    video {
      max-width: 800px;
    }
    <p>Click on video to start playing if it hasn't already started.</p>
    <div id="playvideo">
      <video muted="true" src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"></video>
    </div>

    Note that if your goal is to have the video play with sound, then you would have to create a method of increasing the browser's user engagement metrics for the current page (ie. by using a button to begin playback, or converting to an SPA architecture site to dynamically load content on a pre-existing page that the user has already interacted with).