Greasy Fork is available in English.

Site Filter (Protocol-Independent)

Manage allowed sites dynamically and reference this in other scripts.

Fra og med 13.02.2025. Se den nyeste version.

Dette script bør ikke installeres direkte. Det er et bibliotek, som andre scripts kan inkludere med metadirektivet // @require https://update.greatest.deepsurf.us/scripts/526770/1536607/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.  
  37. async function waitForDocumentReady() {
  38. if (document.readyState === "complete") return;
  39. return new Promise(resolve => {
  40. window.addEventListener("load", resolve, { once: true });
  41. });
  42. }
  43. // ✅ Wait for the script storage key
  44. const key = await waitForScriptStorageKey();
  45. if (!key) return;
  46.  
  47. // ✅ Ensure the document is fully loaded before setting `shouldRunOnThisSite`
  48. await waitForDocumentReady();
  49.  
  50. const STORAGE_KEY = `additionalSites_${key}`; // Unique per script
  51.  
  52. function getDefaultList() {
  53. return [
  54. "*.example.*",
  55. "*example2*"
  56. ];
  57. }
  58. function normalizeUrl(url) {
  59. return url.replace(/^https?:\/\//, ''); // Remove "http://" or "https://"
  60. }
  61. // Load stored additional sites (default is an empty array)
  62. let additionalSites = GM_getValue(STORAGE_KEY, []);
  63. // Merge user-defined sites with default sites (protocols ignored)
  64. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  65. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  66. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  67. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  68. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  69. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  70. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  71. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  72. async function shouldRunOnThisSite() {
  73. const currentFullPath = normalizeUrl(`${window.location.href}`);
  74. return mergedSites.some(pattern => wildcardToRegex(normalizeUrl(pattern)).test(currentFullPath));
  75. }
  76. // function wildcardToRegex(pattern) {
  77. // return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + "$");
  78. // }
  79. /**
  80. * Convert a wildcard pattern (e.g., "*.example.com/index.php?/forums/*") into a valid regex.
  81. * - `*` → Matches any characters (`.*`)
  82. * - `?` → Treated as a **literal question mark** (`\?`)
  83. * - `.` → Treated as a **literal dot** (`\.`)
  84. */
  85. function wildcardToRegex(pattern) {
  86. return new RegExp("^" + pattern
  87. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&') // Escape regex special characters (EXCEPT `.` and `?`)
  88. .replace(/\./g, '\\.') // Ensure `.` is treated as a literal dot
  89. .replace(/\?/g, '\\?') // Ensure `?` is treated as a literal question mark
  90. .replace(/\*/g, '.*') // Convert `*` to `.*` (match any sequence)
  91. + "$");
  92. }
  93. function addCurrentSiteMenu() {
  94. const currentHost = window.location.hostname;
  95. const currentPath = window.location.pathname;
  96. const domainParts = currentHost.split('.');
  97. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  98. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  99. const options = [
  100. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  101. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  102. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  103. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  104. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  105. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  106. ];
  107. const userChoice = prompt(
  108. "Select an option to add the site:\n" +
  109. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  110. "\nEnter a number or cancel."
  111. );
  112. if (!userChoice) return;
  113. const selectedIndex = parseInt(userChoice, 10) - 1;
  114. if (selectedIndex >= 0 && selectedIndex < options.length) {
  115. let pattern = normalizeUrl(options[selectedIndex].pattern);
  116. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  117. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  118. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  119. }
  120. if (!additionalSites.includes(pattern)) {
  121. additionalSites.push(pattern);
  122. GM_setValue(STORAGE_KEY, additionalSites);
  123. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  124. alert(`✅ Added site with pattern: ${pattern}`);
  125. } else {
  126. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  127. }
  128. }
  129. }
  130. function viewIncludedSites() {
  131. //alert(`🔍 Included Sites:\n${mergedSites.join("\n") || "No sites added yet."}`);
  132. alert(`🔍 Included Sites:\n${additionalSites.join("\n") || "No sites added yet."}`);
  133. }
  134. function deleteEntries() {
  135. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  136. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  137. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  138. if (!userChoice) return;
  139. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  140. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  141. GM_setValue(STORAGE_KEY, additionalSites);
  142. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  143. alert("✅ Selected entries have been deleted.");
  144. }
  145. function editEntry() {
  146. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  147. const userChoice = prompt("Select an entry to edit:\n" +
  148. additionalSites.map((item, index) => `${index + 1}. ${item}`).join("\n"));
  149. if (!userChoice) return;
  150. const selectedIndex = parseInt(userChoice, 10) - 1;
  151. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  152. const newPattern = normalizeUrl(prompt("Edit the pattern:", additionalSites[selectedIndex]));
  153. if (newPattern && newPattern.trim() && newPattern !== additionalSites[selectedIndex]) {
  154. additionalSites[selectedIndex] = newPattern.trim();
  155. GM_setValue(STORAGE_KEY, additionalSites);
  156. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  157. alert("✅ Entry updated.");
  158. }
  159. }
  160. function clearAllEntries() {
  161. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  162. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  163. additionalSites = [];
  164. GM_setValue(STORAGE_KEY, additionalSites);
  165. mergedSites = [...getDefaultList()].map(normalizeUrl);
  166. alert("✅ All user-defined entries cleared.");
  167. }
  168. }
  169. function exportAdditionalSites() {
  170. GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  171. alert("📤 Additional sites exported as JSON.");
  172. }
  173. function importAdditionalSites() {
  174. const input = document.createElement("input");
  175. input.type = "file";
  176. input.accept = ".json";
  177. input.onchange = event => {
  178. const reader = new FileReader();
  179. reader.onload = e => {
  180. additionalSites = JSON.parse(e.target.result);
  181. GM_setValue(STORAGE_KEY, additionalSites);
  182. mergedSites = [...new Set([...getDefaultList(), ...additionalSites])].map(normalizeUrl);
  183. alert("📥 Sites imported successfully.");
  184. };
  185. reader.readAsText(event.target.files[0]);
  186. };
  187. input.click();
  188. }
  189. window.shouldRunOnThisSite = shouldRunOnThisSite;
  190. })();
  191. })();