Home » Android » android – Tricks to keep phone from sleeping in mobile web browser using JavaScript/HTML?

android – Tricks to keep phone from sleeping in mobile web browser using JavaScript/HTML?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I know for native mobile applications on Android and iPhone there are easy ways to keep the phone from sleeping, but I am building a mobile web application running in the mobile web browser and would like to explore that possibility.

I have a feeling this isn’t possible for security reasons, but I thought maybe someone has come up with a JavaScript trick or something that works on mobile browsers like mobile Safari, Firefox, or Opera?

How to&Answers:

My experience with setInterval is that it causes memory leaks and increasing memory usage if used over a significant period of time. Using setTimeout is probably useful here, to keep running a small function every minute. That should keep the phone alive without using up excess memory.

On opening the part of the app that you want to keep open,

var id,
    timeout = 600;

id = setTimeout(stayOpen, timeout);

var stayOpen = function () {
  if (stillOnPage) {
    id = setTimeout(stayOpen, timeout);
  }
});

When the user leaves the page you should clear the time out

clearTimeout(id);

EDIT: If this doesn’t work then there may be some action you can take within the stayOpen function which triggers something that will keep the phone awake. Open to suggestions.