Skip to content

Commit 5e577d8

Browse files
committed
add WebSocket connection
1 parent ad6a4cb commit 5e577d8

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/index.ts

+53
Original file line numberDiff line numberDiff line change
@@ -436,3 +436,56 @@ chrome.runtime.onMessage.addListener((message, sender) => {
436436
})
437437
}
438438
})
439+
440+
let activeWebSocket: WebSocket = null;
441+
442+
function connectWebSocket(wsUrl: string | URL) {
443+
if (!wsUrl) {
444+
console.warn("No WebSocket URL provided.");
445+
return;
446+
}
447+
448+
console.log(`Connecting to WebSocket: ${wsUrl}`);
449+
450+
activeWebSocket = new WebSocket(wsUrl);
451+
452+
activeWebSocket.onopen = () => console.log("WebSocket Connected:", wsUrl);
453+
454+
activeWebSocket.onmessage = (event) => console.log("WebSocket Message:", event.data);
455+
456+
activeWebSocket.onerror = (error) => console.error("WebSocket Error:", error);
457+
458+
activeWebSocket.onclose = (event) => {
459+
console.warn(`WebSocket Closed: Code ${event.code}, Reason: ${event.reason}`);
460+
};
461+
}
462+
463+
// Check for WebSocket URLs in Active Origins
464+
chrome.storage.sync.get(["originList"], (data) => {
465+
const originList = JSON.parse(data.originList || "[]");
466+
const wsUrl = originList.find((url: string) => url.startsWith("ws://") || url.startsWith("wss://"));
467+
468+
if (wsUrl) {
469+
connectWebSocket(wsUrl);
470+
}
471+
});
472+
473+
chrome.storage.onChanged.addListener((changes) => {
474+
if (changes.originList) {
475+
const newOriginList = JSON.parse(changes.originList.newValue || "[]");
476+
const wsUrl = newOriginList.find((url: string) => url.startsWith("ws://") || url.startsWith("wss://"));
477+
478+
// Close the WebSocket if it's removed from the list
479+
if (!wsUrl && activeWebSocket) {
480+
console.log("Closing connection.");
481+
activeWebSocket.close();
482+
activeWebSocket = null;
483+
} else if (wsUrl && (!activeWebSocket || activeWebSocket.readyState !== WebSocket.OPEN)) {
484+
// If a new WebSocket URL is found, and WebSocket is not open, reconnect
485+
if (activeWebSocket) {
486+
activeWebSocket.close();
487+
}
488+
connectWebSocket(wsUrl);
489+
}
490+
}
491+
});

0 commit comments

Comments
 (0)