Simple Ad Blocker

A simple userscript ad blocker

目前为 2023-06-01 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Simple Ad Blocker
  3. // @namespace https://bing.com
  4. // @version 0.1
  5. // @description A simple userscript ad blocker
  6. // @match https://*/*
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. (function() {
  11. 'use strict';
  12.  
  13. // A list of filters to block or hide ads
  14. // Each filter is an object with a type (block or hide), a pattern (a string or a regular expression), and an optional domain (a string or an array of strings)
  15. var filters = [
  16. // Block requests to URLs that contain &ad_box_
  17. {type: "block", pattern: "&ad_box_"},
  18. // Hide elements with class name b-popup on hackernoon.com
  19. {type: "hide", pattern: ".b-popup", domain: "hackernoon.com"},
  20. // Hide elements with id ads on any domain
  21. {type: "hide", pattern: "#ads"}
  22. ];
  23.  
  24. // Get the current domain name
  25. var domain = window.location.hostname;
  26.  
  27. // Loop through the filters and apply them
  28. for (var i = 0; i < filters.length; i++) {
  29. var filter = filters[i];
  30. // Check if the filter matches the current domain
  31. if (!filter.domain || filter.domain === domain || (Array.isArray(filter.domain) && filter.domain.includes(domain))) {
  32. // Check if the filter is a block filter
  33. if (filter.type === "block") {
  34. // Intercept and cancel requests to URLs that match the filter pattern
  35. window.addEventListener("beforescriptexecute", function(e) {
  36. var src = e.target.src;
  37. if (src && (typeof filter.pattern === "string" && src.includes(filter.pattern) || filter.pattern.test(src))) {
  38. e.preventDefault();
  39. e.stopPropagation();
  40. console.log("Blocked request to " + src);
  41. }
  42. });
  43. }
  44. // Check if the filter is a hide filter
  45. else if (filter.type === "hide") {
  46. // Hide elements that match the filter pattern using CSS
  47. var style = document.createElement("style");
  48. style.textContent = filter.pattern + " { display: none !important; }";
  49. document.head.appendChild(style);
  50. console.log("Hid elements matching " + filter.pattern);
  51. }
  52. }
  53. }
  54. })();