When we open some video websites, we find that videos can autoplay. However, even if we add "autoplay" or use JavaScript to control it on our own website, it still cannot autoplay.
<body>
<video src="1.mp4" autoplay></video>
</body>
<script>
const vd = document.querySelector('video')
vd.play()
</script>
When we open the console, we will see an error message.
It says that the method failed because the user has not interacted with the page yet. This is due to the autoplay policy of Chrome browser, which is similar to other players. The main purpose is to improve user experience. Otherwise, if you open a website in a crowded place and it suddenly makes strange sounds, it would be embarrassing.
So, what are the solutions? The autoplay policy also explains:
- Allow autoplay with no sound.
- Use an iframe.
- Meet any of the following three conditions:
- The user has interacted with the current domain.
- The user has added the website to the home screen on a mobile device or installed it as a PWA (Progressive Web App).
- On a desktop device, the user's media engagement exceeds the threshold.
What is media engagement? The higher the value, the more interested the browser thinks you are in the content of the website. When it reaches a certain value, it will allow autoplay of videos. You can open chrome://media-engagement/ in Chrome browser to check.
The left side shows the domain visited, and the right side shows the engagement value. The higher the value, the more likely it is to autoplay. However, our website does not have such a high value. So, how can we achieve autoplay?
- Iframe allows the parent window to have autoplay capability and can pass it to the child window, but this is not suitable.
- How can the user have interacted with the website right after opening it?
- Adding the website to the home screen on a mobile device or installing it as a PWA, which is not common in China.
So, only two methods are left:
- Mute the video and let the user manually open the volume.
- Detect that autoplay is not possible and prompt the user to click to play.
Let's see how video websites do it. I have a high media engagement value on Bilibili, so I switched to another computer to take a screenshot. Bilibili uses muted autoplay.
Kuaishou also uses muted autoplay.
Douyin prompts the user to click to play.
Alright, that's all about the methods. Choose the one that suits you.