Function GM_addElement

  • Appends and returns an element with the specified attributes.

    Examples:

    // using a private function in `onload`
    let el = GM_addElement('script', { src: 'https://....' });
    el.onload = () => console.log('loaded', el);

    // same as GM_addStyle('a { color:red }')
    let el = GM_addElement('style', { textContent: 'a { color:red }' });

    // appending to an arbitrary node
    let el = GM_addElement(parentElement.shadowRoot, 'iframe', { src: url });

    Parameters

    • tagName: string

      A tag name like script. Any valid HTML tag can be used, but the only motivation for this API was to add script, link, style elements when they are disallowed by a strict Content-Security-Policy of the site e.g. github.com, twitter.com.

    • Optional attributes: Record<string, string>

      The keys are HTML attributes, not DOM properties, except textContent which sets DOM property textContent. The values are strings so if you want to assign a private function to onload you can do it after the element is created.

    Returns HTMLElement

  • Parameters

    • parentNode: HTMLElement

      The parent node to which the new node will be appended. It can be inside ShadowDOM: someElement.shadowRoot. When omitted, it'll be determined automatically:

      • document.head (<head>) for script, link, style, meta tags.
      • document.body (<body>) for other tags or when there's no <head>.
      • document.documentElement (<html> or an XML root node) otherwise.
    • tagName: string

      A tag name like script. Any valid HTML tag can be used, but the only motivation for this API was to add script, link, style elements when they are disallowed by a strict Content-Security-Policy of the site e.g. github.com, twitter.com.

    • Optional attributes: Record<string, string>

      The keys are HTML attributes, not DOM properties, except textContent which sets DOM property textContent. The values are strings so if you want to assign a private function to onload you can do it after the element is created.

    Returns HTMLElement