URL Replacer/Redirector

Redirect specific sites by replacing part of the URL.

目前为 2021-03-18 提交的版本。查看 最新版本

  1. // ==UserScript==
  2. // @name URL Replacer/Redirector
  3. // @namespace https://github.com/theborg3of5/Userscripts/
  4. // @version 1.1
  5. // @description Redirect specific sites by replacing part of the URL.
  6. // @author Gavin Borg
  7. // @match https://greasyfork.org/en/scripts/403100-url-replacer-redirector
  8. // @grant GM_getValue
  9. // @grant GM_setValue
  10. // ==/UserScript==
  11.  
  12. (function() {
  13. 'use strict';
  14.  
  15. // Initial creation of settings structure if it doesn't exist
  16. if(!GM_getValue("replaceTheseStrings")) {
  17. GM_setValue("replacePrefix", "");
  18. GM_setValue("replaceSuffix", "");
  19. GM_setValue("replaceTheseStrings", {"toReplace": "replaceWith"});
  20. console.log("Created settings structure");
  21. }
  22.  
  23. // Prefix/suffix apply to both sides
  24. var replacePrefix = GM_getValue("replacePrefix");
  25. var replaceSuffix = GM_getValue("replaceSuffix");
  26. var replaceAry = GM_getValue("replaceTheseStrings");
  27. // console.log(replacePrefix, replaceSuffix, replaceAry);
  28.  
  29. var newURL = window.location.href;
  30. for(var key in replaceAry) {
  31. var toReplace = replacePrefix + key + replaceSuffix;
  32. var replaceWith = replacePrefix + replaceAry[key] + replaceSuffix;
  33.  
  34. // Use a RegEx to allow case-insensitive matching
  35. toReplace = new RegExp(escapeRegex(toReplace), "i");
  36.  
  37. newURL = newURL.replace(toReplace, replaceWith);
  38. }
  39. // console.table({"Original URL":window.location.href, "New URL":newURL});
  40.  
  41. if(window.location.href !== newURL) {
  42. window.location.replace(newURL);
  43. }
  44. })();
  45.  
  46. // From https://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript/3561711#3561711
  47. function escapeRegex(string) {
  48. return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
  49. }