Site Filter (Protocol-Independent)

Manage allowed sites dynamically and reference this in other scripts.

2025-02-23 일자. 최신 버전을 확인하세요.

이 스크립트는 직접 설치해서 쓰는 게 아닙니다. 다른 스크립트가 메타 명령 // @require https://update.greatest.deepsurf.us/scripts/526770/1541918/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. if (typeof url !== 'string') {
  60. url = String(url);
  61. }
  62. return url.replace(/^https?:\/\//, ''); // Remove "http://" or "https://"
  63. }
  64. // Load stored additional sites (default is an empty array)
  65. let additionalSites = GM_getValue(STORAGE_KEY, []);
  66.  
  67. let mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  68.  
  69. GM_registerMenuCommand("➕ Add Current Site to Include List", addCurrentSiteMenu);
  70. GM_registerMenuCommand("📜 View Included Sites", viewIncludedSites);
  71. GM_registerMenuCommand("🗑️ Delete Specific Entries", deleteEntries);
  72. GM_registerMenuCommand("✏️ Edit an Entry", editEntry);
  73. GM_registerMenuCommand("🚨 Clear All Entries", clearAllEntries);
  74. GM_registerMenuCommand("📤 Export Site List as JSON", exportAdditionalSites);
  75. GM_registerMenuCommand("📥 Import Site List from JSON", importAdditionalSites);
  76.  
  77. async function shouldRunOnThisSite() {
  78. const currentFullPath = normalizeUrl(`${window.location.href}`);
  79. return mergedSites.some(pattern => wildcardToRegex(normalizeUrl(pattern)).test(currentFullPath));
  80. }
  81. // function wildcardToRegex(pattern) {
  82. // return new RegExp("^" + pattern.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.') + "$");
  83. // }
  84. /**
  85. * Convert a wildcard pattern (e.g., "*.example.com/index.php?/forums/*") into a valid regex.
  86. * - `*` → Matches any characters (`.*`)
  87. * - `?` → Treated as a **literal question mark** (`\?`)
  88. * - `.` → Treated as a **literal dot** (`\.`)
  89. */
  90. function wildcardToRegex(pattern) {
  91. return new RegExp("^" + pattern
  92. .replace(/[-[\]{}()+^$|#\s]/g, '\\$&') // Escape regex special characters (EXCEPT `.` and `?`)
  93. .replace(/\./g, '\\.') // Ensure `.` is treated as a literal dot
  94. .replace(/\?/g, '\\?') // Ensure `?` is treated as a literal question mark
  95. .replace(/\*/g, '.*') // Convert `*` to `.*` (match any sequence)
  96. + "$");
  97. }
  98.  
  99. function addCurrentSiteMenu() {
  100. const currentHost = window.location.hostname;
  101. const currentPath = window.location.pathname;
  102. const domainParts = currentHost.split('.');
  103. const baseDomain = domainParts.length > 2 ? domainParts.slice(-2).join('.') : domainParts.join('.');
  104. const secondLevelDomain = domainParts.length > 2 ? domainParts.slice(-2, -1)[0] : domainParts[0];
  105.  
  106. const options = [
  107. { name: `Preferred Domain Match (*${secondLevelDomain}.*)`, pattern: `*${secondLevelDomain}.*` },
  108. { name: `Base Hostname (*.${baseDomain}*)`, pattern: `*.${baseDomain}*` },
  109. { name: `Base Domain (*.${secondLevelDomain}.*)`, pattern: `*.${secondLevelDomain}.*` },
  110. { name: `Host Contains (*${secondLevelDomain}*)`, pattern: `*${secondLevelDomain}*` },
  111. { name: `Exact Path (${currentHost}${currentPath})`, pattern: normalizeUrl(`${window.location.href}`) },
  112. { name: "Custom Wildcard Pattern", pattern: normalizeUrl(`${window.location.href}`) }
  113. ];
  114.  
  115. const userChoice = prompt(
  116. "Select an option to add the site:\n" +
  117. options.map((opt, index) => `${index + 1}. ${opt.name}`).join("\n") +
  118. "\nEnter a number or cancel."
  119. );
  120.  
  121. if (!userChoice) return;
  122. const selectedIndex = parseInt(userChoice, 10) - 1;
  123. if (selectedIndex >= 0 && selectedIndex < options.length) {
  124. let pattern = normalizeUrl(options[selectedIndex].pattern);
  125. if (options[selectedIndex].name === "Custom Wildcard Pattern") {
  126. pattern = normalizeUrl(prompt("Edit custom wildcard pattern:", pattern));
  127. if (!pattern.trim()) return alert("Invalid pattern. Operation canceled.");
  128. }
  129.  
  130. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", "n").toLowerCase() === 'y';
  131. const postProcessingRequired = prompt("Is post-processing required? (y/n)", "n").toLowerCase() === 'y';
  132.  
  133. const entry = { pattern, preProcessingRequired, postProcessingRequired };
  134.  
  135. if (!additionalSites.some(item => item.pattern === pattern)) {
  136. additionalSites.push(entry);
  137. GM_setValue(STORAGE_KEY, additionalSites);
  138. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  139. alert(`✅ Added site with pattern: ${pattern}`);
  140. } else {
  141. alert(`⚠️ Pattern "${pattern}" is already in the list.`);
  142. }
  143. }
  144. }
  145.  
  146. function viewIncludedSites() {
  147. const siteList = additionalSites.map(item => {
  148. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  149. return `${item.pattern}${status ? ` (${status})` : ''}`;
  150. }).join("\n");
  151. alert(`🔍 Included Sites:\n${siteList || "No sites added yet."}`);
  152. }
  153.  
  154. function deleteEntries() {
  155. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to delete.");
  156. const userChoice = prompt("Select entries to delete (comma-separated numbers):\n" +
  157. additionalSites.map((item, index) => `${index + 1}. ${item.pattern}`).join("\n"));
  158. if (!userChoice) return;
  159. const indicesToRemove = userChoice.split(',').map(num => parseInt(num.trim(), 10) - 1);
  160. additionalSites = additionalSites.filter((_, index) => !indicesToRemove.includes(index));
  161. GM_setValue(STORAGE_KEY, additionalSites);
  162. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  163. alert("✅ Selected entries have been deleted.");
  164. }
  165.  
  166. function editEntry() {
  167. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to edit.");
  168. const userChoice = prompt("Select an entry to edit:\n" +
  169. additionalSites.map((item, index) => {
  170. const status = formatStatus(item.preProcessingRequired, item.postProcessingRequired);
  171. return `${index + 1}. ${item.pattern}${status ? ` (${status})` : ''}`;
  172. }).join("\n"));
  173. if (!userChoice) return;
  174. const selectedIndex = parseInt(userChoice, 10) - 1;
  175. if (selectedIndex < 0 || selectedIndex >= additionalSites.length) return alert("❌ Invalid selection.");
  176. const entry = additionalSites[selectedIndex];
  177. const newPattern = normalizeUrl(prompt("Edit the pattern:", entry.pattern));
  178. if (!newPattern || !newPattern.trim()) return;
  179.  
  180. const preProcessingRequired = prompt("Is pre-processing required? (y/n)", entry.preProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  181. const postProcessingRequired = prompt("Is post-processing required? (y/n)", entry.postProcessingRequired ? "y" : "n").toLowerCase() === 'y';
  182.  
  183. entry.pattern = newPattern.trim();
  184. entry.preProcessingRequired = preProcessingRequired;
  185. entry.postProcessingRequired = postProcessingRequired;
  186. GM_setValue(STORAGE_KEY, additionalSites);
  187. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  188. alert("✅ Entry updated.");
  189. }
  190.  
  191. function clearAllEntries() {
  192. if (additionalSites.length === 0) return alert("⚠️ No user-defined entries to clear.");
  193. if (confirm(`🚨 You have ${additionalSites.length} entries. Clear all?`)) {
  194. additionalSites = [];
  195. GM_setValue(STORAGE_KEY, additionalSites);
  196. mergedSites = [...getDefaultList()].map(normalizeUrl);
  197. alert("✅ All user-defined entries cleared.");
  198. }
  199. }
  200.  
  201. function exportAdditionalSites() {
  202. GM_download("data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(additionalSites, null, 2)), "additionalSites_backup.json");
  203. alert("📤 Additional sites exported as JSON.");
  204. }
  205.  
  206. function importAdditionalSites() {
  207. const input = document.createElement("input");
  208. input.type = "file";
  209. input.accept = ".json";
  210. input.onchange = event => {
  211. const reader = new FileReader();
  212. reader.onload = e => {
  213. additionalSites = JSON.parse(e.target.result);
  214. GM_setValue(STORAGE_KEY, additionalSites);
  215. mergedSites = [...new Set([...getDefaultList(), ...additionalSites.map(item => item.pattern)])].map(normalizeUrl);
  216. alert("📥 Sites imported successfully.");
  217. };
  218. reader.readAsText(event.target.files[0]);
  219. };
  220. input.click();
  221. }
  222.  
  223. function formatStatus(preProcessingRequired, postProcessingRequired) {
  224. if (SHOW_STATUS_ONLY_IF_TRUE && !preProcessingRequired && !postProcessingRequired) {
  225. return '';
  226. }
  227. const preStatus = USE_EMOJI_FOR_STATUS ? (preProcessingRequired ? '✅' : '✖️') : (preProcessingRequired ? 'true' : 'false');
  228. const postStatus = USE_EMOJI_FOR_STATUS ? (postProcessingRequired ? '✅' : '✖️') : (postProcessingRequired ? 'true' : 'false');
  229. return `Pre: ${preStatus}, Post: ${postStatus}`;
  230. }
  231.  
  232. window.shouldRunOnThisSite = shouldRunOnThisSite;
  233. window.isPreProcessingRequired = function() {
  234. const currentFullPath = normalizeUrl(`${window.location.href}`);
  235. const entry = additionalSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  236. return entry ? entry.preProcessingRequired : false;
  237. };
  238. window.isPostProcessingRequired = function() {
  239. const currentFullPath = normalizeUrl(`${window.location.href}`);
  240. const entry = additionalSites.find(item => wildcardToRegex(normalizeUrl(item.pattern)).test(currentFullPath));
  241. return entry ? entry.postProcessingRequired : false;
  242. };
  243. })();
  244. })();