Greasy Fork is available in English.

Site Filter (Protocol-Independent)

Manage allowed sites dynamically and reference this in other scripts.

Tính đến 13-02-2025. Xem phiên bản mới nhất.

Script này sẽ không được không được cài đặt trực tiếp. Nó là một thư viện cho các script khác để bao gồm các chỉ thị meta // @require https://update.greatest.deepsurf.us/scripts/526770/1536599/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. // @run-at document-start
  13. // ==/UserScript==
  14.  
  15. (function () {
  16. 'use strict';
  17.  
  18. // ✅ Wait for `SCRIPT_STORAGE_KEY` to be set
  19. function waitForScriptStorageKey(maxWait = 1000) {
  20. return new Promise(resolve => {
  21. const startTime = Date.now();
  22. const interval = setInterval(() => {
  23. if (typeof window.SCRIPT_STORAGE_KEY !== 'undefined') {
  24. clearInterval(interval);
  25. resolve(window.SCRIPT_STORAGE_KEY);
  26. } else if (Date.now() - startTime > maxWait) {
  27. clearInterval(interval);
  28. console.error("🚨 SCRIPT_STORAGE_KEY is not set! Make sure your script sets it **before** @require.");
  29. resolve(null);
  30. }
  31. }, 50);
  32. });
  33. }
  34.  
  35. (async function initialize() {
  36. const key = await waitForScriptStorageKey();
  37. if (!key) return; // Stop execution if key is not set
  38.  
  39. const STORAGE_KEY = `additionalSites_${key}`; // Unique per script
  40.  
  41. function getDefaultList() {
  42. return [
  43. "*.example.*",
  44. "*example2*"
  45. ];
  46. }
  47. function normalizeUrl(url) {
  48. return url.replace(/^https?:\/\//, ''); // Remove "http://" or "https://"
  49. }
  50. // Load stored additional sites (default is an empty array)
  51. let additionalSites = GM_getValue(STORAGE_KEY, []);
  52. // Merge user-defined sites with default sites (protocols ignored)
  53. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  54. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  55. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  56. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  57. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  58. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  59. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  60. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  61. async function shouldRunOnThisSite() {
  62. const currentFullPath = normalizeUrl(`${window.location.href}`);
  63. return mergedSites.some(pattern => wildcardToRegex(normalizeUrl(pattern)).test(currentFullPath));
  64. }
  65. // function wildcardToRegex(pattern) {
  66. // return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + "$");
  67. // }
  68. /**
  69. * Convert a wildcard pattern (e.g., "*.example.com/index.php?/forums/*") into a valid regex.
  70. * - `*` → Matches any characters (`.*`)
  71. * - `?` → Treated as a **literal question mark** (`\?`)
  72. * - `.` → Treated as a **literal dot** (`\.`)
  73. */
  74. function wildcardToRegex(pattern) {
  75. return new RegExp("^" + pattern
  76. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&') // Escape regex special characters (EXCEPT `.` and `?`)
  77. .replace(/\./g, '\\.') // Ensure `.` is treated as a literal dot
  78. .replace(/\?/g, '\\?') // Ensure `?` is treated as a literal question mark
  79. .replace(/\*/g, '.*') // Convert `*` to `.*` (match any sequence)
  80. + "$");
  81. }
  82. function addCurrentSiteMenu() {
  83. const currentHost = window.location.hostname;
  84. const currentPath = window.location.pathname;
  85. const domainParts = currentHost.split('.');
  86. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  87. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  88. const options = [
  89. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  90. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  91. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  92. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  93. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  94. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  95. ];
  96. const userChoice = prompt(
  97. "Select an option to add the site:\n" +
  98. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  99. "\nEnter a number or cancel."
  100. );
  101. if (!userChoice) return;
  102. const selectedIndex = parseInt(userChoice, 10) - 1;
  103. if (selectedIndex >= 0 && selectedIndex < options.length) {
  104. let pattern = normalizeUrl(options[selectedIndex].pattern);
  105. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  106. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  107. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  108. }
  109. if (!additionalSites.includes(pattern)) {
  110. additionalSites.push(pattern);
  111. GM_setValue(STORAGE_KEY, additionalSites);
  112. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  113. alert(`✅ Added site with pattern: ${pattern}`);
  114. } else {
  115. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  116. }
  117. }
  118. }
  119. function viewIncludedSites() {
  120. //alert(`🔍 Included Sites:\n${mergedSites.join("\n") || "No sites added yet."}`);
  121. alert(`🔍 Included Sites:\n${additionalSites.join("\n") || "No sites added yet."}`);
  122. }
  123. function deleteEntries() {
  124. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  125. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  126. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  127. if (!userChoice) return;
  128. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  129. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  130. GM_setValue(STORAGE_KEY, additionalSites);
  131. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  132. alert("✅ Selected entries have been deleted.");
  133. }
  134. function editEntry() {
  135. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  136. const userChoice = prompt("Select an entry to edit:\n" +
  137. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  138. if (!userChoice) return;
  139. const selectedIndex = parseInt(userChoice, 10) - 1;
  140. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  141. const newPattern = normalizeUrl(prompt("Edit the pattern:", additionalSites[selectedIndex]));
  142. if (newPattern && newPattern.trim() && newPattern !== additionalSites[selectedIndex]) {
  143. additionalSites[selectedIndex] = newPattern.trim();
  144. GM_setValue(STORAGE_KEY, additionalSites);
  145. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  146. alert("✅ Entry updated.");
  147. }
  148. }
  149. function clearAllEntries() {
  150. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  151. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  152. additionalSites = [];
  153. GM_setValue(STORAGE_KEY, additionalSites);
  154. mergedSites = [...getDefaultList()].map(normalizeUrl);
  155. alert("✅ All user-defined entries cleared.");
  156. }
  157. }
  158. function exportAdditionalSites() {
  159. GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  160. alert("📤 Additional sites exported as JSON.");
  161. }
  162. function importAdditionalSites() {
  163. const input = document.createElement("input");
  164. input.type = "file";
  165. input.accept = ".json";
  166. input.onchange = event => {
  167. const reader = new FileReader();
  168. reader.onload = e => {
  169. additionalSites = JSON.parse(e.target.result);
  170. GM_setValue(STORAGE_KEY, additionalSites);
  171. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  172. alert("📥 Sites imported successfully.");
  173. };
  174. reader.readAsText(event.target.files[0]);
  175. };
  176. input.click();
  177. }
  178. window.shouldRunOnThisSite = shouldRunOnThisSite;
  179. })();
  180. })();