-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
102 lines (87 loc) · 2.4 KB
/
Copy pathbackground.js
File metadata and controls
102 lines (87 loc) · 2.4 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
let ws;
let DEVICE_ID = "Desktop";
let retryTimeout = 5000; // 5s retry
let isConnecting = false;
let intervalId = null;
let listenersRegistered = false;
init();
async function init() {
const { serverPort = 3210 } = await chrome.storage.local.get("serverPort");
tryConnect(serverPort);
}
async function tryConnect(port) {
if (isConnecting) return;
isConnecting = true;
try {
const res = await fetch(`http://localhost:${port}/ip`, { cache: "no-store" });
const { ip, wsPort } = await res.json();
const SERVER = `ws://${ip}:${wsPort}`;
console.log("Auto-connecting to:", SERVER);
ws = new WebSocket(SERVER);
ws.onopen = () => {
console.log("✅ Connected to TabSync server");
sendTabs();
if (!intervalId) {
intervalId = setInterval(sendTabs, 60000);
}
if (!listenersRegistered) {
chrome.tabs.onRemoved.addListener(sendTabs);
chrome.tabs.onCreated.addListener(sendTabs);
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (
changeInfo.status === "complete" ||
changeInfo.url
) {
sendTabs();
}
});
listenersRegistered = true;
}
isConnecting = false;
};
ws.onclose = () => {
console.warn("❌ Disconnected from TabSync server. Retrying...");
isConnecting = false;
setTimeout(() => tryConnect(port), retryTimeout);
};
ws.onerror = (err) => {
console.error("WebSocket error:", err);
ws.close();
};
ws.onmessage = (e) => console.log("Message:", e.data);
} catch (err) {
console.log(`TabSync Local: could not find server on port ${port}`, err);
setTimeout(() => {
isConnecting = false;
tryConnect(port);
}, retryTimeout);
}
}
function sendTabs() {
chrome.tabs.query({}, (tabs) => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
deviceId: DEVICE_ID,
tabs: tabs.map((t) => ({ title: t.title, url: t.url })),
})
);
}
});
}
chrome.runtime.onMessage.addListener((msg) => {
if (msg.action === "reconnect") {
if (ws) ws.close();
init(); // will read new port and reconnect
}
});
chrome.runtime.onSuspend.addListener(() => {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(
JSON.stringify({
deviceId: DEVICE_ID,
tabs: [],
})
);
}
});