Rohit Ailani
Rohit Ailani

Reputation: 910

prevent safari from sleep using javascript

I am implementing a javascript timer the timer loads in an iframe and that timer also plays some audio files at certain intervals, basically it is for routine exercises so say for 10 seconds there is first exercise and then for a minute the second one and for 2 minutes the third one and so on.

As the time for a exercise completes and the next one turns up I change the audio for that particular exercise and so on. What I want is to prevent the browser to sleep in each and every mode that is phone(android, iOS), laptop everywhere till the time the timer is running.

I have used 2 solutions for ios I am using to reload the page and for the others whether it is android or laptop I am trying a video as stated here.

And my final code to check things is

var ua = {
  Android: /Android/ig.test(navigator.userAgent),
  // iOS: /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
  iOS:/iPhone|iPad|iPod/i.test(navigator.userAgent)
};

<script type="text/javascript" src="js/sleep.js"></script>

if (ua.iOS) {
  preventIosSleep = setInterval(function(){
    window.top.location.href = '/';
    setTimeout(function(){
      try {
        window.top.stop();
      } catch (exception) {
        document.execCommand('Stop');
      }
    }, 0);
  }, 10000);
} else {
  sleep.prevent();
}

// and when releasing the things
if (ua.iOS) {
  clearInterval(preventIosSleep);
} else {
  sleep.allow();
}

The sleep.js is taken from the link as told above. Have been trying things for around a week now. This solution works well on all browsers except the safari on MAC. Can any one tell me how can I stop the safari browser not to enter the sleep mode.

Upvotes: 11

Views: 2256

Answers (2)

Jeff Woodard
Jeff Woodard

Reputation: 647

I'd recommend creating a cordova app if you're looking for device level control. I believe the type of thing you're hoping to accomplish in a browser is something Apple actively prevents; probably for battery life and/or device security reasons.

If you go that route, You could use: https://github.com/EddyVerbruggen/Insomnia-PhoneGap-Plugin

Hope it helps.

Upvotes: 2

vbguyny
vbguyny

Reputation: 1172

In the past you have been able to do hacks such as having an audio tag on the page or reloading a URL in a hidden iframe. But none of these work as of iOS 7. The only workable solution is to create an app which uses the UIWebView.

Below is the for additional information if you are interested: https://stackoverflow.com/a/7477438/1640090

Upvotes: 7

Related Questions