How to autoplay video in a website when mobile device is on low power mode
Including videos in a webpage can cause lot of trouble while making it compatible for all browsers and devices.
One of such situation is autoplaying video when the mobile device is on low power mode or data saving mode.
Low power mode, as the name suggests, it saves the battery of the device as much as it can by various means.
One of them is by disabling autoplay of media items such as videos.
So how can we tackle this situation?
Here is a little hack to overcome this situation.
What we can do is, we can detect whether video is playable or not and show a UI (such as play icon) to force playing of video or play the video on user iteraction (Such as clicking a button or user touches the screen of device).
Here is the little script to get the job done:
First of all add a property to the video item for checking whether the video is already playing or not
Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function () {
return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}
});
The devices which are in low power mode, invokes the ‘suspend’ event.
So, you can show a play button only when the devices are in low power mode.
To do that add a event listener for ‘suspend’ to show your UI for playing video manually:
const videoElement = document.getElementById('ID_of_video');
videoElement.addEventListener('suspend', () => {
// suspend invoked
// show play button
});
videoElement.addEventListener('play', () => {
// video is played
// remove play button UI
});
Also, if you don’t want to use a ‘play button UI’ to play video manually, attach a event listener to body or any other element such as video container to play video as soon as user interact with the device.
** Note: In low power mode, video cannot be played unless user interact with the device **
** Note: This little hack also fix the video autoplaying issue on safari browsers **
So attach a event listener to the body to detect any click or touch and then play video on that event:
$('body').on('click touchstart', function () {
const videoElement = document.getElementById('home_video');
if (videoElement.playing) {
// video is already playing so do nothing
}
else {
// video is not playing
// so play video now
videoElement.play();
}
});
This little script can save you lot of work and efforts to tackles issue of autoplaying of videos on all devices and browsers.
Also the video is: muted loop playsinline autoplay
Below is a working example of this:
To test this, try turning ‘low power mode on’ on your device and this video will still autoplay iteself: