Skip to content

Instantly share code, notes, and snippets.

@Kein
Created July 14, 2023 18:52
Show Gist options
  • Save Kein/4c1a8cb20b246047c9fbc8e35ec2ead1 to your computer and use it in GitHub Desktop.
Save Kein/4c1a8cb20b246047c9fbc8e35ec2ead1 to your computer and use it in GitHub Desktop.
/* eslint-disable no-empty */
// Subscribe to events
chrome.tabs.onRemoved.addListener(OnAnyTabRemoved);
// Spawn offscreen page
// Apaprently it needs to be async to be caugh, for whatever reason
(async () => {
try { await chrome.offscreen.createDocument({ url: '/pages/offscreen.html', reasons: [chrome.offscreen.Reason.CLIPBOARD], justification: ''}); }
catch (error) { console.log(error); }
})();
// LOGIC
function OnAnyTabRemoved(tabId: number, removeInfo: chrome.tabs.TabRemoveInfo): void
{
const data: TabClosedInfo = { tabID: tabId, removeInfo: removeInfo };
DispatchMessage(Action.TABREMOVED, Target.OFFSCREEN, data, false, `Tab ${tabId} removed`);
}
function DispatchMessage(action: Action, target: Target, data: any, waitForAnser: boolean, message: string): boolean
{
let result = false;
const msg: APIMessage = {
action: action,
result: data !== null,
data: data,
target: target,
source: Target.WORKER,
message: message
};
try {
if (!waitForAnser) {
chrome.runtime.sendMessage(msg);
}
else
{
chrome.runtime.sendMessage(msg, (response: APIMessage) => {
if (!response || !response.source || response.source !== msg.target) {
console.log('Invalid response received');
}
else {
console.log('Response: ', response.message);
result = response.result;
}
});
}
}
catch(error) { console.log('Dispatch Error:', error); }
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment