Skip to content

Commit

Permalink
Don't reregister contentscripts if not necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
ajayyy committed Aug 11, 2023
1 parent 93d695e commit 6aeefaa
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 17 deletions.
39 changes: 23 additions & 16 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,27 @@ chrome.runtime.onInstalled.addListener(function () {
* @param {JSON} options
*/
async function registerFirefoxContentScript(options: Registration) {
if ("scripting" in chrome && "getRegisteredContentScripts" in chrome.scripting) {
// Bug in Firefox where you need to use browser namespace for this call
const getContentScripts = async (filter: browser.scripting.ContentScriptFilter) => {
if (isFirefoxOrSafari()) {
return await browser.scripting.getRegisteredContentScripts(filter);
} else {
return await chrome.scripting.getRegisteredContentScripts(filter);
}
};

const existingRegistrations = await getContentScripts({
ids: [options.id]
});

if (existingRegistrations.length > 0
&& existingRegistrations[0].matches.every((match) => options.matches.includes(match))) {
// No need to register another script, already registered
return;
}
}

await unregisterFirefoxContentScript(options.id);

if ("scripting" in chrome && "getRegisteredContentScripts" in chrome.scripting) {
Expand Down Expand Up @@ -180,25 +201,11 @@ async function registerFirefoxContentScript(options: Registration) {
* Only works on Firefox.
* Firefox requires that this is handled by the background script
*/
async function unregisterFirefoxContentScript(id: string) {
async function unregisterFirefoxContentScript(id: string) {
if ("scripting" in chrome && "getRegisteredContentScripts" in chrome.scripting) {
// Bug in Firefox where you need to use browser namespace for this call
const getContentScripts = async (filter: browser.scripting.ContentScriptFilter) => {
if (isFirefoxOrSafari()) {
return await browser.scripting.getRegisteredContentScripts(filter);
} else {
return await chrome.scripting.getRegisteredContentScripts(filter);
}
};

const existingRegistrations = await getContentScripts({
await chrome.scripting.unregisterContentScripts({
ids: [id]
});
if (existingRegistrations?.length > 0) {
await chrome.scripting.unregisterContentScripts({
ids: existingRegistrations.map((script) => script.id),
});
}
} else {
if (contentScriptRegistrations[id]) {
contentScriptRegistrations[id].unregister();
Expand Down
1 change: 0 additions & 1 deletion src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ export default class Utils {
if (!isFirefoxOrSafari() || isSafari()) {
permissions.push("webNavigation");
}
console.log(permissions)

chrome.permissions.request({
origins: this.getPermissionRegex(),
Expand Down

0 comments on commit 6aeefaa

Please sign in to comment.