Force RTL

This script will change the direction of the elements with arabic characters

  1. // ==UserScript==
  2. // @license JazzMedo
  3. // @name Force RTL
  4. // @version 0.72
  5. // @description This script will change the direction of the elements with arabic characters
  6. // @author JazzMedo
  7. // @match https://*
  8. // @include https://*
  9. // @icon https://cdn-icons-png.flaticon.com/512/6212/6212766.png
  10. // @grant none
  11. // @namespace https://greasyfork.org/users/1420266
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16. function updateTextDirections() {
  17. document.querySelectorAll("*").forEach((element) => {
  18. // Check if the element contains Arabic characters using Unicode range
  19. const arabicRegex =
  20. /[\u0600-\u06FF\u0750-\u077F\u08A0-\u08FF\uFB50-\uFDFF\uFE70-\uFEFF]/;
  21.  
  22. // Check only direct text content of the element (not nested elements)
  23. const textNodes = Array.from(element.childNodes).filter(
  24. (node) => node.nodeType === Node.TEXT_NODE
  25. );
  26.  
  27. const hasArabic = textNodes.some((node) =>
  28. arabicRegex.test(node.textContent)
  29. );
  30.  
  31. if (hasArabic && element.parentElement) {
  32. element.parentElement.setAttribute("dir", "rtl");
  33. }
  34. });
  35. }
  36.  
  37. // Run on initial load
  38. updateTextDirections();
  39.  
  40. // Run again whenever new content is added
  41. // (e.g., after AJAX calls or dynamic element creation)
  42. const observer = new MutationObserver((mutationsList) => {
  43. for (const mutation of mutationsList) {
  44. if (mutation.type === "childList" || mutation.type === "characterData") {
  45. updateTextDirections();
  46. break;
  47. }
  48. }
  49. });
  50.  
  51. observer.observe(document.body, {
  52. childList: true,
  53. subtree: true,
  54. characterData: true,
  55. });
  56. })();