Prevent Mobile Browser From Sleeping

By  on  

Web developers still have a difficult job when it comes to mobile; the web will never provide as many APIs or as much control as native mobile platforms but our users expect the same excellent experience.  Creating HTML5 games and media-heavy apps for the web can be really difficult, as you really have to pay attention to performance the the rest of the little things that native platforms provide.

One of those small features includes preventing the device from sleeping when the user hasn't been active.  Imagine your user playing a game that doesn't require much interaction, experiencing a VR demo, or even just a blog post or slideshow, and the screen suddenly goes black -- that's an annoyance that your users may not (and shouldn't have to) tolerate.  That's where NoSleep.js comes in: a small Wake Lock API shim to prevent the browser and device from going to sleep!

Using NoSleep.js is super easy.  To start the no sleep effect, simply add:

var noSleep = new NoSleep();

function enableNoSleep() {
  noSleep.enable();
  document.removeEventListener('touchstart', enableNoSleep, false);
}

// Enable wake lock.
// (must be wrapped in a user input event handler e.g. a mouse or touch handler)
document.addEventListener('touchstart', enableNoSleep, false);

Once you want to cede control of sleep, simply call the disable method:

// Disable wake lock at some point in the future.
// (does not need to be wrapped in any user input event handler)
noSleep.disable();

So how does NoSleep.js prevent the sleep effect?  NoSleep.js mocks a tiny mp4 video and continuously plays it, which works because browsers know enough to not signal sleep when a video is playing.  What a clever way to prevent the device from sleeping!

Will we ever get a JavaScript API that allows us to control whether the device sleeps or  not?  Possibly -- no browser vendor has committed to the Wake Lock API yet.  That's why us web developers have to stay clever and take matters into our own hands!

Recent Features

  • By
    Facebook Open Graph META Tags

    It's no secret that Facebook has become a major traffic driver for all types of websites.  Nowadays even large corporations steer consumers toward their Facebook pages instead of the corporate websites directly.  And of course there are Facebook "Like" and "Recommend" widgets on every website.  One...

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

Incredible Demos

  • By
    Dynamic Waveform Visualizations with wavesurfer.js

    Waveform images are an awesome addition to boring audio widgets.  They can be functional as well as aesthetically pleasing, allowing users to navigate audio visually.  I recently found wavesurfer.js, an amazing waveform image utility that uses to Web Audio API to create super customizable...

  • By
    jQuery Chosen Plugin

    Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes...

Discussion

  1. Jon

    It seems the specification exists but has not yet been implemented in mobile browsers.
    https://w3c.github.io/wake-lock/

  2. Awesome! I think this might be very helpful for my friend! Keep up the good work! :)

  3. Lubos

    How does this affect the battery life?

  4. Hi David,
    Can you please check whether this code will work or not?

    /navigator.wakeLock is the main standby API property. 
    //request method requests the computer to not enter standby mode. Here "display" indicates that the monitor shouldn't enter standby mode.
    navigator.wakeLock.request("display").then(
        function successFunction() {
            // success
        },
        function errorFunction() {
            // error
        }
    //here system indicates CPU, GPU, radio, wifi etc.
    navigator.wakeLock.request("system").then(
        function successFunction() {
            // success
        },
        function errorFunction() {
            // error
        }
    ); 
    
    //release() is used to release the lock.
    navigator.wakeLock.release("display");
    

    I got this from some forums and I didn’t tried this.

    • @ezhil Why can’t you try it?

    • Fany

      no work, 2018-11-27, Android 8.1, Chrome 70

  5. Ric

    Such a clever way! Thanks!

  6. Prov94

    It looks very interesting and I need something similar like this. The good is, its working on Android 8 and Chrome browser, but the problem is the screen light, I would like to reduce the screen brightness.
    The better solution I require for my webapp is, that the screen can be locked, but the browser stay alive and is not going in sleep mode, due my web app is requesting periodically over XHR data from a server and has to ring if the data which are new in database arrive on phone.
    So thats the problem, I hope with Wake Lock API in future will be solved.

  7. I believe that an iOS update broke this on native Safari, sometime in the last few weeks.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!