0

For some demo purposes, I'd like to add a toolbar at the very top of a page for better live demo capabilities. That means I don't know the structure of the web page, as I am running live demos on different web ages of customers. Currently, my script works on some pages quite well on others not.

Using developer Tools, for me, it looks like the main pain is when there is a class in the body, and I assume this is added dynamically by some logic. Open up the page then in Chrome - Developer tools, I can see my DIV at the top of the page, but closing the developer tools, it looks like the class in the body is overlaying my toolbar.

What I have tried is:

window.parent.document.body.insertBefore(toolbar, document.body.firstChild);

or

document.body.insertBefore(toolbar, document.body.firstChild);

and certainly the option in Tampermonkey:

// @run-at document-end

But unfortunately with no luck.

I case anybody has found a more stable way to add something at the top of te page would be much appreciated under the awareness, when I don't know the page, there might be room to fail.

Thank you!

Frank
  • 780
  • 1
  • 10
  • 22

2 Answers2

0

As an alternative to the insertBefore, you can try out insertAdjacentElement. But I have a feeling that this is not the main issue. You don't really need the toolbar to be at the "first" position of your DOM. You might need to place it anywhere and place it at the top by CSS with absolute or fixed positioning and huge z-index value in order to place it on top of everything.

koloml
  • 525
  • 2
  • 15
0

Try:

// ==UserScript==
// @name         ___TEST-DELETE-ME
// @namespace    http://tampermonkey.net/
// @version      0.1
// @match        https://updat.cc/*
// @grant        none
// ==/UserScript==

(function() {

    const $ = document.querySelector.bind(document);
    setTimeout(() => {
        $('body').insertAdjacentHTML('afterbegin', init_css() );
    },1500);

})();
function init_css(){
    return `
        <div id="disTestDiv">Voila, ca march!</div>
        <style>
            #disTestDiv{z-index:99999999;position:fixed;top:10vh;left:0;width:100vw;text-align:center;font-size:5rem;color:blue;}
        </style>
        `;
}

Notes:

  1. This is not jQuery (look carefully)

  2. I used a setTimeout to be sure the page is ready to receive the info. (i.e. will not immediately overwrite your newly-injected HTML with something else). It is FREQUENTLY necessary to use setTimeout (old way) or a MutatationObserver (new way) to ensure your injected code works.

  3. Note that we are injecting both the HTML and the CSS at the same time. You don't have to do it this way, but nice to know you can. You also can inject additional javascript this way, fwiw.

cssyphus
  • 37,875
  • 18
  • 96
  • 111