diff --git a/background.js b/background.js index d02b4f3..87f8321 100644 --- a/background.js +++ b/background.js @@ -1 +1,54 @@ -console.log("Service Worker Is Running!") \ No newline at end of file +let socket; +const connectWebsocket = url => { + disconnectWebsocket() + socket = new WebSocket(url); + socket.onopen = () => { + chrome.runtime.sendMessage({status: "connected"}) + } + socket.onclose = () => { + chrome.runtime.sendMessage({status: "disconnected"}) + } +} + +const disconnectWebsocket = () => { + if (socket) { + try { + socket.close() + socket = null; + } catch(e) { + + } + } +} + +heartbeat = () => { + if (socket) { + if (socket.readyState === WebSocket.OPEN) { + try { + socket.send(JSON.stringify({ + "type": "heartbeat", + })) + } catch(e) { + console.error("Error sending heartbeat:", e); + } + } else { + disconnectWebsocket() + } + } +} +heartbeat() +setInterval(heartbeat, 3000) + +console.info("Chrome Extenstion Background is loaded") +chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) { + if (msg.action === "connectWebsocket") { + console.info("Start to connect websocket") + connectWebsocket(msg.url) + } else if (msg.action === "init") { + if (socket) { + chrome.runtime.sendMessage({status: "connected"}) + } else { + chrome.runtime.sendMessage({status: "initialized"}) + } + } +}) diff --git a/popup.html b/popup.html index 43ab9f2..2f1c665 100644 --- a/popup.html +++ b/popup.html @@ -1,10 +1,13 @@ + - Popup + WebSocket Connector -

My Chrome Extension

-

This is a sample popup.

+

+ + + \ No newline at end of file diff --git a/popup.js b/popup.js new file mode 100644 index 0000000..4230840 --- /dev/null +++ b/popup.js @@ -0,0 +1,14 @@ +document.getElementById('connectBtn').addEventListener('click', () => { + let wsUrl = document.getElementById('wsUrl').value; + if (!wsUrl) { + wsUrl = 'ws://127.0.0.1:8881/?token=a' + } + const msg = { + action: "connectWebsocket", url: wsUrl, + }; + chrome.runtime.sendMessage(msg) +}) + +chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => { + document.getElementById("wsStatus").innerText = msg.status; +}); \ No newline at end of file