From 0284d913ef95f1196a6a4e04854834d0851225e7 Mon Sep 17 00:00:00 2001 From: Mai Trung Duc Date: Tue, 20 Feb 2024 00:16:24 +0800 Subject: [PATCH] refactor: remove interval check --- package.json | 2 +- src/pages/content/index.ts | 49 +++++++++++--------------------------- 2 files changed, 15 insertions(+), 36 deletions(-) diff --git a/package.json b/package.json index 877073d..0a4ac94 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "konva-inspector", - "version": "0.0.19", + "version": "0.0.21", "description": "Devtools for your Konva App", "license": "MIT", "repository": { diff --git a/src/pages/content/index.ts b/src/pages/content/index.ts index 5704ad3..8ff63d2 100644 --- a/src/pages/content/index.ts +++ b/src/pages/content/index.ts @@ -1,53 +1,32 @@ detect(); -const interval = setInterval(detect, 5000); -let count = 0; -let shouldBroadcastToBackground = true; function detect(requestDetectionCallback?: (data: any) => void) { try { - const s = document.createElement("script"); - s.src = chrome.runtime.getURL("src/pages/detector/index.js"); + const s = document.createElement('script'); + s.src = chrome.runtime.getURL('src/pages/detector/index.js'); document.body.appendChild(s); s.onload = () => { - document.addEventListener( - "__KONVA_DEVTOOLS__DETECTION_RESULT", - function (e: CustomEvent) { - if (shouldBroadcastToBackground) { - chrome.runtime - .sendMessage({ - type: "__KONVA_DEVTOOLS__BROADCAST_RESULT", - result: e.detail, - }) - .catch(() => { - // stop sending to background script if connection between content_script <-> background_script is failed - shouldBroadcastToBackground = false; - }) - .finally(() => { - // clear interval once detected or reach limit - // otherwise the interval can run thousands of times (after few mins) when connection is failed (not sure why, probably when background_script becomes inactive?), and browser will get hanged - if (e.detail || count >= 10) { - clearInterval(interval); - } else { - count++; - } - }); - } + document.addEventListener('__KONVA_DEVTOOLS__DETECTION_RESULT', function (e: CustomEvent) { + chrome.runtime + .sendMessage({ + type: '__KONVA_DEVTOOLS__BROADCAST_RESULT', + result: e.detail, + }) + .catch(() => {}); - s.remove(); - requestDetectionCallback && requestDetectionCallback(e.detail); - } - ); + s.remove(); + requestDetectionCallback && requestDetectionCallback(e.detail); + }); - document.dispatchEvent(new CustomEvent("__KONVA_DEVTOOLS__DETECT_KONVA")); + document.dispatchEvent(new CustomEvent('__KONVA_DEVTOOLS__DETECT_KONVA')); }; } catch (error) { - clearInterval(interval); console.log(error); } } chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) { - if (request["type"] === "__KONVA_DEVTOOLS__REQUEST_DETECTION") { + if (request['type'] === '__KONVA_DEVTOOLS__REQUEST_DETECTION') { detect(sendResponse); } return true; // this make sure sendResponse will work asynchronously