mirror of
https://github.com/yaklang/yaklang-chrome-extension.git
synced 2026-09-26 21:21:53 +08:00
add popup.js and background
This commit is contained in:
+54
-1
@@ -1 +1,54 @@
|
||||
console.log("Service Worker Is Running!")
|
||||
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"})
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user