/
_ping.js.erb
70 lines (54 loc) · 1.69 KB
/
_ping.js.erb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
var frequency = <%= frequency %> * 1000;
var warning = <%= warning %> * 1000;
var start = <%= start %> * 1000;
var warning_info = "<%= j render('session_timeout/warning') %>";
function ping() {
var request = new XMLHttpRequest();
request.open('GET', '/active', true);
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
success(JSON.parse(request.responseText));
}
};
request.send();
setTimeout(ping, frequency);
}
function success(data) {
var el = document.getElementById('session-timeout-msg'),
cntnr = document.getElementById('session-timeout-cntnr');
var time_timeout = new Date(data.timeout).getTime(),
time_cutoff = new Date().getTime() + warning,
show_warning = time_timeout < time_cutoff;
if (show_warning & !el) {
cntnr.insertAdjacentHTML('afterbegin', warning_info);
initTimer(warning);
}
if (!show_warning & el) el.remove();
if (data.live == false) {
window.onbeforeunload = null;
window.onunload = null;
window.location.href = '/timeout';
}
}
function initTimer(duration) {
var ctdn = document.getElementById('ctdn');
var time_left = duration;
var interval = 1000;
var format = function(ms) {
var s = ms / 1000;
var min = parseInt(s / 60, 10);
var sec = parseInt(s % 60, 10);
return (min == 0 ? '' :
min + ' minute' + (min !== 1 ? 's' : '') + ' and ') +
sec + ' second' + (sec !== 1 ? 's' : '');
}
function tick() {
ctdn.innerHTML = format(time_left);
if (time_left <= 0) return;
time_left -= interval;
setTimeout(tick, interval);
}
tick();
}
setTimeout(ping, start);