Skip to content

Commit 0b6e0cb

Browse files
committed
doesUrlMatchPatterns
1 parent 25c0860 commit 0b6e0cb

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

index.ts

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,24 @@ export function isValidPattern(matchPattern: string): boolean {
2020
return matchPattern === '<all_urls>' || patternValidationRegex.test(matchPattern);
2121
}
2222

23+
export function doesUrlMatchPatterns(url: string, ...matchPattern: string[]): boolean {
24+
if (matchPattern.includes('<all_urls>') && allUrlsRegex.test(url)) {
25+
return true;
26+
}
27+
28+
if (matchPattern.includes('*://*/*') && allStarsRegex.test(url)) {
29+
return true;
30+
}
31+
32+
for (const pattern of matchPattern) {
33+
if (patternToRegex(pattern).test(url)) {
34+
return true;
35+
}
36+
}
37+
38+
return false;
39+
}
40+
2341
function getRawPatternRegex(matchPattern: string): string {
2442
assertValidPattern(matchPattern);
2543

readme.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
patternToRegex,
2424
globToRegex,
2525
excludeDuplicatePatterns
26+
doesUrlMatchPatterns,
2627
assertValidPattern,
2728
isValidPattern,
2829
} from 'webext-patterns';
@@ -112,6 +113,15 @@ excludeDuplicatePatterns([
112113
// Returns ["https://*/*"]
113114
```
114115

116+
#### doesUrlMatchPatterns(url, ...patterns)
117+
118+
Accepts a URL and any number of patterns and returns `true` if the URL matches any of the patterns. This is a convenience method that wraps `patternToRegex` for single use. If you plan on testing multiple URLs to the same pattern, it's better to convert the patterns to a regex once and reuse that.
119+
120+
```js
121+
doesUrlMatchPatterns('https://google.com/', ['https://*.google.com/*', '*://example.com/*']);
122+
// Returns true
123+
```
124+
115125
#### assertValidPattern(pattern)
116126

117127
Accepts a pattern and throws an error if it's invalid.

test/patterns.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,13 @@
11
import test from 'ava';
2-
import {patternToRegex, isValidPattern, assertValidPattern} from '../index.js';
2+
import {patternToRegex, isValidPattern, assertValidPattern, doesUrlMatchPatterns} from '../index.js';
33

44
function macro(t, pattern, matching) {
55
const regex = patternToRegex(pattern);
66
for (const url of matching) {
77
t.regex(url, regex);
88
t.true(isValidPattern(pattern));
99
t.notThrows(() => assertValidPattern(pattern));
10+
t.true(doesUrlMatchPatterns(url, 'http://never.example.com/*', pattern, 'http://nope.example.com/*'));
1011
}
1112
}
1213

0 commit comments

Comments
 (0)