3

There are extensions that make small on-page popups that in Inspection in Chrome show as #shadow-root(open).

I want to customise its styles with Tampermonkey, but using GM_addStyle(".class_name{zoom: 166%;}"); doesn't work. On native elements it works.

double-beep
  • 5,031
  • 17
  • 33
  • 41
user3529406
  • 55
  • 1
  • 7
  • Create a `style` element with document.createElement and append it to that element's shadowRoot. – wOxxOm Feb 17 '20 at 13:08
  • You can see the example here: https://stackoverflow.com/questions/11668111/how-do-i-pop-up-a-custom-form-dialog-in-a-greasemonkey-script – Szelek Jun 24 '21 at 07:42

2 Answers2

0

GM_addStyle() appends the <style> element it creates to the <head>, therefore it can't modify the styling of Shadow DOM elements. You need to use GM_addElement().

// ==UserScript==
// @name         Shadow DOM styling
// @version      0.1
// @author       double-beep
// @match        http*://example.com
// @grant        GM_addElement
// ==/UserScript==

(function() {
    'use strict';

    const shadowRoot = document.querySelector('element');
    const styles = `div { color: red; }`;

    GM_addElement(shadowRoot, 'style', { textContent: styles });
})();

If the styles aren't applied, you can create a <script> element instead in a similar way:

GM_addElement(shadowRoot, 'script', {
    textContent: 'shadowRootElement.shadowRoot.querySelector("...").style.color = "red";'
});
double-beep
  • 5,031
  • 17
  • 33
  • 41
-1

You need to insert the style tag into the shadow root.

(pinching some code from this answer)

function addStyleToShadowRoot(shadowRoot,css) {
    const style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    shadowRoot.appendChild(style);
}

Call it like this:

addStyleToShadowRoot(customElement.shadowRoot, myCss);
Sam Hasler
  • 12,344
  • 10
  • 72
  • 106