-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_script.js
More file actions
78 lines (66 loc) · 2.39 KB
/
content_script.js
File metadata and controls
78 lines (66 loc) · 2.39 KB
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
71
72
73
74
75
76
77
78
(function() {
let pingInterval = null;
let lastActivity = Date.now();
const ACTIVITY_EVENTS = ['mousemove', 'keydown', 'mousedown', 'touchstart', 'scroll'];
const hostname = location.hostname || location.href;
let idleThreshold = 60;
function safeSendMessage(msg) {
if (!chrome.runtime || !chrome.runtime.id) return; // <--- provjera
try {
chrome.runtime.sendMessage(msg, () => {
if (chrome.runtime.lastError) {
const m = chrome.runtime.lastError.message || "";
if (!m.includes("Extension context invalidated")) {
console.warn("Message error:", m);
}
}
});
} catch (e) {
if (!String(e).includes("Extension context invalidated")) {
console.error("sendMessage failed:", e);
}
}
}
chrome.storage.local.get(['settings'], res => {
if (res.settings && res.settings.idleThresholdSeconds)
idleThreshold = res.settings.idleThresholdSeconds;
});
function startPinging() {
if (pingInterval) return;
safeSendMessage({ type: 'ping', hostname });
pingInterval = setInterval(() => {
safeSendMessage({ type: 'ping', hostname });
}, 1000);
// Ako ekstenzija nestane - automatski prekini pinganje
setInterval(() => {
if (!chrome.runtime || !chrome.runtime.id) stopPinging();
}, 3000);
}
function stopPinging() {
if (!pingInterval) return;
clearInterval(pingInterval);
pingInterval = null;
}
function userBecameActive() {
lastActivity = Date.now();
if (document.visibilityState === 'visible' && document.hasFocus()) startPinging();
}
function maybeStopIfIdle() {
const idleSeconds = (Date.now() - lastActivity) / 1000;
if (idleSeconds >= idleThreshold) stopPinging();
}
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible' && document.hasFocus()) {
if ((Date.now() - lastActivity) / 1000 < idleThreshold) startPinging();
} else stopPinging();
});
window.addEventListener('focus', () => {
if ((Date.now() - lastActivity) / 1000 < idleThreshold) startPinging();
});
window.addEventListener('blur', () => stopPinging());
ACTIVITY_EVENTS.forEach(evt => {
window.addEventListener(evt, userBecameActive, { passive: true });
});
setInterval(maybeStopIfIdle, 2000);
if (document.visibilityState === 'visible' && document.hasFocus()) userBecameActive();
})();