In my service worker script I want to open an offscreen page when there is a new tab among tabs and close it if no new tabs present
function hasOffscreenDocument() {
if ('getContexts' in chrome.runtime) {
return chrome.runtime.getContexts({
contextTypes: ['OFFSCREEN_DOCUMENT'],
}).then(contexts => Boolean(contexts.length));
} else {
return clients.matchAll().then((matchedClients) =>
matchedClients.some(client => {
client.url.includes(chrome.runtime.id);
}
));
}
}
let isClosingOffscreenDocument = null;
let isCreatingOffscreenDocument = null;
function createOffscreenDocument() {
return hasOffscreenDocument().then((hasDocument) => {
if (!hasDocument) {
return chrome.offscreen.createDocument({
url: "offscreen.html",
reasons: [chrome.offscreen.Reason.DOM_PARSER],
justification: 'Parse xml documents using offscreen document',
}).finally(() => {
isCreatingOffscreenDocument = null;
});
}
});
}
function closeOffsceenDocument() {
return hasOffscreenDocument().then((hasDocument) => {
if (hasDocument) {
return chrome.offscreen.closeDocument().finally(() => {
isClosingOffscreenDocument = null;
});
}
});
}
chrome.tabs.onCreated.addListener(() => {
if (!isCreatingOffscreenDocument) {
isCreatingOffscreenDocument = chrome.tabs.query({}).then((tabs) => {
if (tabs.some((tab) => tab.pendingUrl === "chrome://newtab/")) {
return createOffscreenDocument(() => console.log("SUCCESS"))
}
});
}
});
chrome.tabs.onRemoved.addListener(() => {
if (!isClosingOffscreenDocument) {
isClosingOffscreenDocument = chrome.tabs.query({}).then((tabs) => {
if (!tabs.some((tab) => tab.pendingUrl === "chrome://newtab/")) {
return closeOffsceenDocument();
}
});
}
});
My extension also replaces new tab page (in manifest)
"chrome_url_overrides": {
"newtab": "newtab.html"
},
No resources are being loaded in these html documents
The problem is:First I open a lot of NTP tabs and some others (
google.com / chrome://extensions, whatever). After that, I close my browser, and when I reopen it, a warning appears about incorrectly closing the browser with a suggestion to restore previously closed tabs.
There is no such problem if the extension is disabled.
What could I be doing wrong?