Site Filter (Protocol-Independent)

Manage allowed sites dynamically and reference this in other scripts.

目前为 2025-02-13 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/526770/1536571/Site%20Filter%20%28Protocol-Independent%29.js

  1. // ==UserScript==
  2. // @name Site Filter (Protocol-Independent)
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.0
  5. // @description Manage allowed sites dynamically and reference this in other scripts.
  6. // @author blvdmd
  7. // @match *://*/*
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // @grant GM_registerMenuCommand
  11. // @grant GM_download
  12. // ==/UserScript==
  13.  
  14. (function () {
  15. 'use strict';
  16.  
  17. const STORAGE_KEY = "additionalSites";
  18.  
  19. function getDefaultList() {
  20. return [
  21. "*.example.*",
  22. "*example2*"
  23. ];
  24. }
  25.  
  26. function normalizeUrl(url) {
  27. return url.replace(/^https?:\/\//, ''); // Remove "http://" or "https://"
  28. }
  29.  
  30. // Load stored additional sites (default is an empty array)
  31. let additionalSites = GM_getValue(STORAGE_KEY, []);
  32.  
  33. // Merge user-defined sites with default sites (protocols ignored)
  34. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  35.  
  36. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  37. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  38. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  39. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  40. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  41. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  42. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  43.  
  44. async function shouldRunOnThisSite() {
  45. const currentFullPath = normalizeUrl(`${window.location.href}`);
  46. return mergedSites.some(pattern => wildcardToRegex(normalizeUrl(pattern)).test(currentFullPath));
  47. }
  48.  
  49. // function wildcardToRegex(pattern) {
  50. // return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + "$");
  51. // }
  52.  
  53. /**
  54. * Convert a wildcard pattern (e.g., "*.example.com/index.php?/forums/*") into a valid regex.
  55. * - `*` → Matches any characters (`.*`)
  56. * - `?` → Treated as a **literal question mark** (`\?`)
  57. * - `.` → Treated as a **literal dot** (`\.`)
  58. */
  59. function wildcardToRegex(pattern) {
  60. return new RegExp("^" + pattern
  61. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&') // Escape regex special characters (EXCEPT `.` and `?`)
  62. .replace(/\./g, '\\.') // Ensure `.` is treated as a literal dot
  63. .replace(/\?/g, '\\?') // Ensure `?` is treated as a literal question mark
  64. .replace(/\*/g, '.*') // Convert `*` to `.*` (match any sequence)
  65. + "$");
  66. }
  67.  
  68.  
  69. function addCurrentSiteMenu() {
  70. const currentHost = window.location.hostname;
  71. const currentPath = window.location.pathname;
  72. const domainParts = currentHost.split('.');
  73. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  74. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  75.  
  76. const options = [
  77. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  78. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  79. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  80. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  81. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  82. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  83. ];
  84.  
  85. const userChoice = prompt(
  86. "Select an option to add the site:\n" +
  87. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  88. "\nEnter a number or cancel."
  89. );
  90.  
  91. if (!userChoice) return;
  92. const selectedIndex = parseInt(userChoice, 10) - 1;
  93. if (selectedIndex >= 0 && selectedIndex < options.length) {
  94. let pattern = normalizeUrl(options[selectedIndex].pattern);
  95. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  96. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  97. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  98. }
  99. if (!additionalSites.includes(pattern)) {
  100. additionalSites.push(pattern);
  101. GM_setValue(STORAGE_KEY, additionalSites);
  102. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  103. alert(`✅ Added site with pattern: ${pattern}`);
  104. } else {
  105. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  106. }
  107. }
  108. }
  109.  
  110. function viewIncludedSites() {
  111. //alert(`🔍 Included Sites:\n${mergedSites.join("\n") || "No sites added yet."}`);
  112. alert(`🔍 Included Sites:\n${additionalSites.join("\n") || "No sites added yet."}`);
  113. }
  114.  
  115. function deleteEntries() {
  116. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  117. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  118. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  119. if (!userChoice) return;
  120. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  121. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  122. GM_setValue(STORAGE_KEY, additionalSites);
  123. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  124. alert("✅ Selected entries have been deleted.");
  125. }
  126.  
  127. function editEntry() {
  128. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  129. const userChoice = prompt("Select an entry to edit:\n" +
  130. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  131. if (!userChoice) return;
  132. const selectedIndex = parseInt(userChoice, 10) - 1;
  133. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  134. const newPattern = normalizeUrl(prompt("Edit the pattern:", additionalSites[selectedIndex]));
  135. if (newPattern && newPattern.trim() && newPattern !== additionalSites[selectedIndex]) {
  136. additionalSites[selectedIndex] = newPattern.trim();
  137. GM_setValue(STORAGE_KEY, additionalSites);
  138. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  139. alert("✅ Entry updated.");
  140. }
  141. }
  142.  
  143. function clearAllEntries() {
  144. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  145. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  146. additionalSites = [];
  147. GM_setValue(STORAGE_KEY, additionalSites);
  148. mergedSites = [...getDefaultList()].map(normalizeUrl);
  149. alert("✅ All user-defined entries cleared.");
  150. }
  151. }
  152.  
  153. function exportAdditionalSites() {
  154. GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  155. alert("📤 Additional sites exported as JSON.");
  156. }
  157.  
  158. function importAdditionalSites() {
  159. const input = document.createElement("input");
  160. input.type = "file";
  161. input.accept = ".json";
  162. input.onchange = event => {
  163. const reader = new FileReader();
  164. reader.onload = e => {
  165. additionalSites = JSON.parse(e.target.result);
  166. GM_setValue(STORAGE_KEY, additionalSites);
  167. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  168. alert("📥 Sites imported successfully.");
  169. };
  170. reader.readAsText(event.target.files[0]);
  171. };
  172. input.click();
  173. }
  174.  
  175. window.shouldRunOnThisSite = shouldRunOnThisSite;
  176. })();