Skip to content

Commit

Permalink
Add excludeMatches support to getTabsByUrl
Browse files Browse the repository at this point in the history
  • Loading branch information
fregante committed Jan 16, 2023
1 parent 8ddd8f2 commit 8dc6595
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
24 changes: 24 additions & 0 deletions index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,28 @@ describe('getTabsByUrl', () => {
'It should pass the query to chrome.tabs',
);
});

it('should handle the `excludeMatches` array', async () => {
const excludeMatches = ['http://*/*'];
assert.deepEqual(
await getTabsByUrl([], excludeMatches),
[],
'No patterns means no tabs',
);
assert.deepEqual(
await getTabsByUrl(['https://example.com/*'], excludeMatches),
[1],
'It should pass the query to chrome.tabs',
);
assert.deepEqual(
await getTabsByUrl(['*://*/*'], excludeMatches),
[1],
'It should exclude tabs with URLs matching `excludeMatches`',
);
assert.deepEqual(
await getTabsByUrl(['http://no-way.example.com/*'], excludeMatches),
[],
'It should exclude tabs with URLs matching `excludeMatches`, even if it’s the only match',
);
});
});
13 changes: 9 additions & 4 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import chromeP from 'webext-polyfill-kinda';
import type {ExtensionTypes} from 'webextension-polyfill';
import {patternToRegex} from 'webext-patterns';
import type {ContentScript} from './types.js';

const gotScripting = typeof chrome === 'object' && 'scripting' in chrome;
Expand Down Expand Up @@ -192,13 +193,17 @@ export async function executeScript(
}
}

export async function getTabsByUrl(patterns: string[]): Promise<number[]> {
if (patterns.length === 0) {
export async function getTabsByUrl(matches: string[], excludeMatches?: string[]): Promise<number[]> {
if (matches.length === 0) {
return [];
}

const tabs = await chromeP.tabs.query({url: patterns});
return tabs.map(tab => tab.id).filter((id): id is number => typeof id === 'number');
const exclude = excludeMatches ? patternToRegex(...excludeMatches) : undefined;

const tabs = await chromeP.tabs.query({url: matches});
return tabs
.filter(tab => tab.id && tab.url && (exclude ? !exclude.test(tab.url) : true))
.map(tab => tab.id!);
}

export async function injectContentScript(
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
}
},
"dependencies": {
"webext-patterns": "^1.2.0",
"webext-polyfill-kinda": "^0.10.0"
},
"devDependencies": {
Expand Down

0 comments on commit 8dc6595

Please sign in to comment.