Skip to content

Commit

Permalink
refactor: remove interval check
Browse files Browse the repository at this point in the history
  • Loading branch information
maitrungduc1410 committed Feb 19, 2024
1 parent 67ce36e commit 0284d91
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 36 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "konva-inspector",
"version": "0.0.19",
"version": "0.0.21",
"description": "Devtools for your Konva App",
"license": "MIT",
"repository": {
Expand Down
49 changes: 14 additions & 35 deletions src/pages/content/index.ts
Original file line number Diff line number Diff line change
@@ -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
Expand Down

0 comments on commit 0284d91

Please sign in to comment.