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/1536564/Site%20Filter%20%28Protocol-Independent%29.js

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