Open Source Shadow DOM

Ensure all Shadow DOM nodes are open. Includes workarounds for broken functionality due to Shadow DOM restriction. Intented for research use.

  1. // ==UserScript==
  2. // @name Open Source Shadow DOM
  3. // @namespace https://greasyfork.org/en/users/85671-jcunews
  4. // @version 1.1.3
  5. // @license AGPLv3
  6. // @author jcunews
  7. // @description Ensure all Shadow DOM nodes are open. Includes workarounds for broken functionality due to Shadow DOM restriction. Intented for research use.
  8. // @match *://*/*
  9. // @grant none
  10. // @inject-into page
  11. // @run-at document-start
  12. // ==/UserScript==
  13.  
  14. (d => {
  15. //fix document.activeElement not able to get element in Shadow DOM
  16. var dac = (d = Object.getOwnPropertyDescriptor(Document.prototype, "activeElement")).get;
  17. d.get = function() {
  18. var p = dac.call(this), n;
  19. while (n = p.shadowRoot?.activeElement) p = n;
  20. return p
  21. };
  22. Object.defineProperty(Document.prototype, "activeElement", d);
  23.  
  24. //make sure Shadow DOMs are open
  25. var as = Element.prototype.attachShadow;
  26. Element.prototype.attachShadow = function(opts) {
  27. var o = {}, m = opts?.mode, r;
  28. Array.from(Object.entries(opts)).forEach(a => o[a[0]] = a[1]);
  29. o.mode = "open";
  30. opts = o;
  31. r = as.apply(this, arguments);
  32. if (m === "closed") {
  33. Object.defineProperty(r, "realMode", {value: "open"});
  34. Object.defineProperty(r, "mode", {
  35. get: () => "closed",
  36. set: v => v
  37. })
  38. }
  39. return r
  40. };
  41.  
  42. //fix event not dispatching if it came from element in Shadow DOM
  43. var dael = Document.addEventListener;
  44. Document.addEventListener = function(typ, fn) {
  45. function f(e) {
  46. if (e.shadowRoot) {
  47. e.shadowRoot.addEventListener.apply(e.shadowRoot, arguments);
  48. e.shadowRoot.querySelectorAll('*').forEach(f)
  49. }
  50. }
  51. document.querySelectorAll('body,body *').forEach(f);
  52. return dael.apply(this, arguments)
  53. };
  54. })()