javascripttampermonkey

How to insert a note node in the DOM at the top of any web page?


I try to add a text box if the REQUEST_URI have an entry note like this:

enter image description here

By example: https://stackoverflow.com/?note=TEST don't produce any new node from my code.

// ==UserScript==
// @name         Simple note from QUERY_STRING
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Affiche la valeur de 'note' de la query string de l'URL.
// @author       Mévatlavé
// @match        *://*/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    function addNoteHeader(noteValue) {
        const header = document.createElement('div');
        header.className = 'query-string-notifier';
        header.textContent = noteValue;
        header.style.backgroundColor = 'yellow';
        header.style.color = 'black';
        header.style.fontSize = '24px';
        header.style.fontWeight = 'bold';
        header.style.textAlign = 'center';
        header.style.padding = '10px';
        header.style.position = 'fixed';
        header.style.top = '0';
        header.style.left = '0';
        header.style.right = '0';
        header.style.zIndex = '1000';

        document.body.insertBefore(header, document.body.firstChild);
    }

    const urlParams = new URLSearchParams(window.location.search);
    const noteValue = urlParams.get('note');

    if (noteValue) {
        addNoteHeader(noteValue);
    }
})();

It works on some sites, but not others. What's the cause?
Is my issue is CSP or DOM loading related?
How to fix or workaround to work on any website?


Solution

  • Instead of trying to add an element on the top of the page, my experience is that using a side box is more reliable and works on most web sites including SO:

            const sidebar = document.createElement('div');
            sidebar.className = 'note-sidebar';
            sidebar.style.position = 'fixed';
            sidebar.style.top = '30%'; // Positionne la note dans le premier tiers de la fenêtre
            sidebar.style.right = '0';
            sidebar.style.zIndex = '9999';
            sidebar.style.backgroundColor = 'yellow';
            sidebar.style.padding = '5px'; // Réduit le padding
            sidebar.style.fontSize = '16px'; // Réduit la taille de la police
            sidebar.style.color = 'black';
            sidebar.style.textAlign = 'center';
            sidebar.style.width = '150px'; // Largeur de la boîte dépliée
            sidebar.style.minHeight = '30px'; // Hauteur minimale pour le replié
            sidebar.style.transition = 'width 0.3s'; // Transition pour l'animation de largeur