Skip to content

Commit

Permalink
fix(content-scripts): reconnect when port disconnected
Browse files Browse the repository at this point in the history
  • Loading branch information
moreal committed Jun 18, 2024
1 parent 9c00cfb commit 28867c8
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions content-scripts/src/injectsdk.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
const scriptElement = document.createElement("script");
scriptElement.src = chrome.runtime.getURL("content-scripts/global.js");
// Functions
function connect() {
return chrome.runtime.connect({
name: "content-script",
})
}

const port = chrome.runtime.connect({
name: "content-script",
});

port.onMessage.addListener((res, _) => {
function portMessagelistener(res: any, port: chrome.runtime.Port) {
const messageId = res.messageId;

if (res && typeof res === "object" && res.hasOwnProperty("error")) {
Expand Down Expand Up @@ -33,9 +33,20 @@ port.onMessage.addListener((res, _) => {
result: res.result,
});
}
});
};

function portDisconnectlistener(port: chrome.runtime.Port) {
port.onDisconnect.removeListener(portDisconnectlistener);
port.onMessage.removeListener(portMessagelistener);

port = connect();

port.onDisconnect.addListener(portDisconnectlistener);
port.onMessage.addListener(portMessagelistener);
};


window.addEventListener("message", async function (event) {
async function windowMessageListener(event: MessageEvent) {
if (event.source != window) return;

if (!event.data.type || event.data.type !== "FROM_PAGE") {
Expand Down Expand Up @@ -123,5 +134,17 @@ window.addEventListener("message", async function (event) {
event.source.origin,
);
}
});
}

// Setup
const scriptElement = document.createElement("script");
scriptElement.src = chrome.runtime.getURL("content-scripts/global.js");

let port = connect();

port.onDisconnect.addListener(portDisconnectlistener);
port.onMessage.addListener(portMessagelistener);

window.addEventListener("message", windowMessageListener);

document.documentElement.appendChild(scriptElement).remove();

0 comments on commit 28867c8

Please sign in to comment.