瀏覽代碼

fix: match query and hash if existed in match rules

close #443
Gerald 7 年之前
父節點
當前提交
9893f03db9
共有 2 個文件被更改,包括 29 次插入5 次删除
  1. 9 5
      src/background/utils/tester.js
  2. 20 0
      test/background/tester.js

+ 9 - 5
src/background/utils/tester.js

@@ -53,16 +53,14 @@ export function testScript(url, script) {
   const inc = mergeLists(custom.origInclude && meta.include, custom.include);
   const exc = mergeLists(custom.origExclude && meta.exclude, custom.exclude);
   const excMat = mergeLists(custom.origExcludeMatch && meta.excludeMatch, custom.excludeMatch);
-  // Match patterns works only on scheme, host and path.
-  const baseUrl = url.split('#')[0].split('?')[0];
   // match all if no @match or @include rule
   let ok = !mat.length && !inc.length;
   // @match
-  ok = ok || testMatch(baseUrl, mat);
+  ok = ok || testMatch(url, mat);
   // @include
   ok = ok || testGlob(url, inc);
   // @exclude-match
-  ok = ok && !testMatch(baseUrl, excMat);
+  ok = ok && !testMatch(url, excMat);
   // @exclude
   ok = ok && !testGlob(url, exc);
   return ok;
@@ -125,7 +123,13 @@ function hostMatcher(rule) {
   };
 }
 function pathMatcher(rule) {
-  const reRule = new RegExp(str2RE(rule));
+  const iHash = rule.indexOf('#');
+  let iQuery = rule.indexOf('?');
+  let strRe = str2RE(rule);
+  if (iQuery > iHash) iQuery = -1;
+  if (iQuery < 0 && iHash < 0) strRe = `${strRe.slice(0, -1)}(?:[?#]|$)`;
+  else if (iHash < 0) strRe = `${strRe.slice(0, -1)}(?:#|$)`;
+  const reRule = new RegExp(strRe);
   return data => reRule.test(data);
 }
 function matchTester(rule) {

+ 20 - 0
test/background/tester.js

@@ -125,6 +125,26 @@ test('path', t => {
     q.end();
   });
 
+  t.test('should match query string and hash if existed in rules', q => {
+    const script = buildScript({
+      meta: {
+        match: [
+          'https://www.google.com/a?query',
+          'https://www.google.com/b#hash',
+          'https://www.google.com/c?query#hash',
+        ],
+      },
+    });
+    q.notOk(testScript('https://www.google.com/a', script), 'should match query');
+    q.notOk(testScript('https://www.google.com/b', script), 'should match hash');
+    q.ok(testScript('https://www.google.com/a?query', script), 'should match query');
+    q.ok(testScript('https://www.google.com/a?query#hash', script), 'should match query and ignore hash');
+    q.notOk(testScript('https://www.google.com/b?query#hash', script), 'should match query and hash');
+    q.ok(testScript('https://www.google.com/b#hash', script), 'should match hash');
+    q.ok(testScript('https://www.google.com/c?query#hash', script), 'should match query and hash');
+    q.end();
+  });
+
   t.end();
 });