Last active
August 29, 2015 14:08
-
-
Save pronebird/e8b87fb81dde9b0127ac to your computer and use it in GitHub Desktop.
iOS 8 standalone apps screen lock detector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Detect screenlock on standalone ios apps and replace content with message to reload the app | |
// When user locks screen on iOS 8 devices, everything dies except web workers | |
// This will definitely drain battery. | |
// Based on the idea by ajayel: http://stackoverflow.com/a/26091749/351305 | |
// | |
(function () { | |
var WORKER_URI = '/app/worker.js'; | |
var TIMEOUT = 2000; | |
// run on iOS 8+ only | |
if(!window.navigator.standalone || window.navigator.userAgent.toLowerCase().indexOf('os 8_') === -1) { | |
return; | |
} | |
var t = { | |
tok: null, | |
tik: null, | |
pan: false, | |
worker: null, | |
interval: null | |
}; | |
function stopWork() { | |
t.worker.terminate(); | |
clearInterval(t.interval); | |
t.worker = null; | |
t.interval = null; | |
} | |
function startWork() { | |
t.worker = new Worker(WORKER_URI); | |
t.tik = t.tok = +new Date(); | |
t.worker.onmessage = function onmessage (e) { | |
var d = JSON.parse(e.data); | |
if(d.message === 'tiktok') { | |
// ignored delayed messages (due to touchmove) | |
if(d.result < t.tok) { | |
return; | |
} | |
t.tok = d.result; | |
var diff = Math.abs(t.tik - t.tok); | |
if(diff > TIMEOUT * 2) { | |
stopWork(); | |
document.write('Please restart app after locking the screen. Apple are working to prevent this issue.'); | |
} | |
} | |
} | |
t.interval = setInterval(function () { | |
t.tik = +new Date(); | |
}, TIMEOUT); | |
} | |
window.addEventListener('touchmove', function () { | |
if(!t.pan) { | |
t.tok = t.tik = +new Date(); | |
t.pan = true; | |
} | |
}); | |
window.addEventListener('touchend', function () { | |
if(t.pan) { | |
t.tok = t.tik = +new Date(); | |
t.pan = false; | |
} | |
}); | |
startWork(); | |
})(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function () { | |
setInterval(function () { | |
postMessage(JSON.stringify({ | |
message: "tiktok", | |
result: +new Date() | |
})); | |
}, 1000); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment