CSS Helper - URL Attribute Adder

Adds a custom attribute (url-url) to all body tags, to make it easier for CSS extensions to target specific URL's.

  1. // ==UserScript==
  2. // @name CSS Helper - URL Attribute Adder
  3. // @description Adds a custom attribute (url-url) to all body tags, to make it easier for CSS extensions to target specific URL's.
  4. // @namespace Violentmonkey Scripts
  5. // @match *://*/*
  6. // @grant none
  7. // @version 1.0
  8. // @author Jupiter Liar
  9. // @license Attribution CC BY
  10. // @description 8/26/2023, 5:09:26 AM
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. // Function to set the URL attribute on the body tag
  17. function setUrlAttribute() {
  18. document.body.setAttribute('url-url', window.location.href);
  19. }
  20.  
  21. // Initial setup
  22. setUrlAttribute();
  23.  
  24. // Watch for URL changes using MutationObserver on the body tag
  25. const observer = new MutationObserver(() => {
  26. setUrlAttribute();
  27. });
  28.  
  29. observer.observe(document.body, {
  30. childList: true,
  31. subtree: true
  32. });
  33.  
  34. // Watch for popstate event to capture back/forward navigation
  35. window.addEventListener('popstate', setUrlAttribute);
  36.  
  37. // Watch for changes in pushState/replaceState to capture dynamic URL changes
  38. const originalPushState = history.pushState;
  39. const originalReplaceState = history.replaceState;
  40.  
  41. history.pushState = function(...args) {
  42. const result = originalPushState.apply(this, args);
  43. setUrlAttribute();
  44. return result;
  45. };
  46.  
  47. history.replaceState = function(...args) {
  48. const result = originalReplaceState.apply(this, args);
  49. setUrlAttribute();
  50. return result;
  51. };
  52. })();