Site Filter (Protocol-Independent)

Manage allowed sites dynamically and reference this in other scripts.

As of 23.02.2025. See ბოლო ვერსია.

ეს სკრიპტი არ უნდა იყოს პირდაპირ დაინსტალირებული. ეს ბიბლიოთეკაა, სხვა სკრიპტებისთვის უნდა ჩართეთ მეტა-დირექტივაში // @require https://update.greatest.deepsurf.us/scripts/526770/1541914/Site%20Filter%20%28Protocol-Independent%29.js.

  1. // ==UserScript==
  2. // @name Site Filter (Protocol-Independent)
  3. // @namespace http://tampermonkey.net/
  4. // @version 2.1
  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. const USE_EMOJI_FOR_STATUS = true; // Configurable flag to use emoji for true/false status
  19. const SHOW_STATUS_ONLY_IF_TRUE = true; // Configurable flag to show status only if any value is true
  20.  
  21. function waitForScriptStorageKey(maxWait = 1000) {
  22. return new Promise(resolve => {
  23. const startTime = Date.now();
  24. const interval = setInterval(() => {
  25. if (typeof window.SCRIPT_STORAGE_KEY !== 'undefined') {
  26. clearInterval(interval);
  27. resolve(window.SCRIPT_STORAGE_KEY);
  28. } else if (Date.now() - startTime > maxWait) {
  29. clearInterval(interval);
  30. console.error("🚨 SCRIPT_STORAGE_KEY is not set! Make sure your script sets it **before** @require.");
  31. resolve(null);
  32. }
  33. }, 50);
  34. });
  35. }
  36.  
  37. (async function initialize() {
  38.  
  39. async function waitForDocumentReady() {
  40. if (document.readyState === "complete") return;
  41. return new Promise(resolve => {
  42. window.addEventListener("load", resolve, { once: true });
  43. });
  44. }
  45. // ✅ Wait for the script storage key
  46. const key = await waitForScriptStorageKey();
  47. if (!key) return;
  48.  
  49. // ✅ Ensure the document is fully loaded before setting `shouldRunOnThisSite`
  50. await waitForDocumentReady();
  51.  
  52. const STORAGE_KEY = `additionalSites_${key}`;
  53.  
  54. function getDefaultList() {
  55. return typeof window.GET_DEFAULT_LIST === "function" ? window.GET_DEFAULT_LIST() : [];
  56. }
  57.  
  58. function normalizeUrl(url) {
  59. return url.replace(/^https?:\/\//, '');
  60. }
  61. // Load stored additional sites (default is an empty array)
  62. let additionalSites = GM_getValue(STORAGE_KEY, []);
  63.  
  64. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  65.  
  66. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  67. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  68. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  69. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  70. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  71. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  72. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  73.  
  74. async function shouldRunOnThisSite() {
  75. const currentFullPath = normalizeUrl(`${window.location.href}`);
  76. return mergedSites.some(pattern => wildcardToRegex(normalizeUrl(pattern)).test(currentFullPath));
  77. }
  78. // function wildcardToRegex(pattern) {
  79. // return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + "$");
  80. // }
  81. /**
  82. * Convert a wildcard pattern (e.g., "*.example.com/index.php?/forums/*") into a valid regex.
  83. * - `*` → Matches any characters (`.*`)
  84. * - `?` → Treated as a **literal question mark** (`\?`)
  85. * - `.` → Treated as a **literal dot** (`\.`)
  86. */
  87. function wildcardToRegex(pattern) {
  88. return new RegExp("^" + pattern
  89. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&') // Escape regex special characters (EXCEPT `.` and `?`)
  90. .replace(/\./g, '\\.') // Ensure `.` is treated as a literal dot
  91. .replace(/\?/g, '\\?') // Ensure `?` is treated as a literal question mark
  92. .replace(/\*/g, '.*') // Convert `*` to `.*` (match any sequence)
  93. + "$");
  94. }
  95.  
  96. function addCurrentSiteMenu() {
  97. const currentHost = window.location.hostname;
  98. const currentPath = window.location.pathname;
  99. const domainParts = currentHost.split('.');
  100. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  101. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  102.  
  103. const options = [
  104. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  105. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  106. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  107. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  108. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  109. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  110. ];
  111.  
  112. const userChoice = prompt(
  113. "Select an option to add the site:\n" +
  114. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  115. "\nEnter a number or cancel."
  116. );
  117.  
  118. if (!userChoice) return;
  119. const selectedIndex = parseInt(userChoice, 10) - 1;
  120. if (selectedIndex >= 0 && selectedIndex < options.length) {
  121. let pattern = normalizeUrl(options[selectedIndex].pattern);
  122. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  123. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  124. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  125. }
  126.  
  127. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", "n").toLowerCase() === 'y';
  128. const postProcessingRequired = prompt("Is post-processing required? (y/n)", "n").toLowerCase() === 'y';
  129.  
  130. const entry = { pattern, preProcessingRequired, postProcessingRequired };
  131.  
  132. if (!additionalSites.some(item => item.pattern === pattern)) {
  133. additionalSites.push(entry);
  134. GM_setValue(STORAGE_KEY, additionalSites);
  135. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  136. alert(`✅ Added site with pattern: ${pattern}`);
  137. } else {
  138. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  139. }
  140. }
  141. }
  142.  
  143. function viewIncludedSites() {
  144. const siteList = additionalSites.map(item => {
  145. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  146. return `${item.pattern}${status ? ` (${status})` : ''}`;
  147. }).join("\n");
  148. alert(`🔍 Included Sites:\n${siteList || "No sites added yet."}`);
  149. }
  150.  
  151. function deleteEntries() {
  152. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  153. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  154. additionalSites.map((item, index) => `${index + 1}. ${item.pattern}`).join("\n"));
  155. if (!userChoice) return;
  156. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  157. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  158. GM_setValue(STORAGE_KEY, additionalSites);
  159. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  160. alert("✅ Selected entries have been deleted.");
  161. }
  162.  
  163. function editEntry() {
  164. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  165. const userChoice = prompt("Select an entry to edit:\n" +
  166. additionalSites.map((item, index) => {
  167. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  168. return `${index + 1}. ${item.pattern}${status ? ` (${status})` : ''}`;
  169. }).join("\n"));
  170. if (!userChoice) return;
  171. const selectedIndex = parseInt(userChoice, 10) - 1;
  172. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  173. const entry = additionalSites[selectedIndex];
  174. const newPattern = normalizeUrl(prompt("Edit the pattern:", entry.pattern));
  175. if (!newPattern || !newPattern.trim()) return;
  176.  
  177. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", entry.preProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  178. const postProcessingRequired = prompt("Is post-processing required? (y/n)", entry.postProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  179.  
  180. entry.pattern = newPattern.trim();
  181. entry.preProcessingRequired = preProcessingRequired;
  182. entry.postProcessingRequired = postProcessingRequired;
  183. GM_setValue(STORAGE_KEY, additionalSites);
  184. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  185. alert("✅ Entry updated.");
  186. }
  187.  
  188. function clearAllEntries() {
  189. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  190. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  191. additionalSites = [];
  192. GM_setValue(STORAGE_KEY, additionalSites);
  193. mergedSites = [...getDefaultList()].map(normalizeUrl);
  194. alert("✅ All user-defined entries cleared.");
  195. }
  196. }
  197.  
  198. function exportAdditionalSites() {
  199. GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  200. alert("📤 Additional sites exported as JSON.");
  201. }
  202.  
  203. function importAdditionalSites() {
  204. const input = document.createElement("input");
  205. input.type = "file";
  206. input.accept = ".json";
  207. input.onchange = event => {
  208. const reader = new FileReader();
  209. reader.onload = e => {
  210. additionalSites = JSON.parse(e.target.result);
  211. GM_setValue(STORAGE_KEY, additionalSites);
  212. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  213. alert("📥 Sites imported successfully.");
  214. };
  215. reader.readAsText(event.target.files[0]);
  216. };
  217. input.click();
  218. }
  219.  
  220. function formatStatus(preProcessingRequired, postProcessingRequired) {
  221. if (SHOW_STATUS_ONLY_IF_TRUE && !preProcessingRequired && !postProcessingRequired) {
  222. return '';
  223. }
  224. const preStatus = USE_EMOJI_FOR_STATUS ? (preProcessingRequired ? '✅' : '✖️') : (preProcessingRequired ? 'true' : 'false');
  225. const postStatus = USE_EMOJI_FOR_STATUS ? (postProcessingRequired ? '✅' : '✖️') : (postProcessingRequired ? 'true' : 'false');
  226. return `Pre: ${preStatus}, Post: ${postStatus}`;
  227. }
  228.  
  229. window.shouldRunOnThisSite = shouldRunOnThisSite;
  230. window.isPreProcessingRequired = function() {
  231. const currentFullPath = normalizeUrl(`${window.location.href}`);
  232. const entry = additionalSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  233. return entry ? entry.preProcessingRequired : false;
  234. };
  235. window.isPostProcessingRequired = function() {
  236. const currentFullPath = normalizeUrl(`${window.location.href}`);
  237. const entry = additionalSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  238. return entry ? entry.postProcessingRequired : false;
  239. };
  240. })();
  241. })();